在 C# 中返回多个 类

Returning multiple classes in c#

我有一个函数 return 是一个新的 class 取决于输入字符串。

private classX GetData(string id)
{
   if (id == "-string1")
       return new class1(this, @"path");
   if (id == "-string2")
       return new class2(this, @"path");
   if (id == "-string3")
       return new class3(this, @"path");

   // ...

   return null;
}

问题是,我想要一个条件(例如“-all”),即 return 一个接一个 class。我不知道该怎么做。 有什么办法可以将return那些class一个一个地return吗?因为我知道它不会与 'return' 一起使用,因为它结束了代码,所以其余部分无法访问。

只需将其设为 return classX 数组即可。除了使用数组或 List

之外,没有其他方法

您可以将函数更改为 return 一个数组,然后遍历该数组。 如果是 class,它将是数组的第一个元素。

您必须 return 一组实例,而不是单个实例。如果 classX 是 class 的基础 class 1,2,3 只是 return classX 的 IEnumerable 而不是单个实例。然后,您可以使用 yield return 来 return 您想要的 class 1 到 3 的所有实例。

也就是说,这是一种非常奇怪的生成 classes 的方式,总体上我不建议这样做。

首先,如果可能的话,你应该让你所有的 classes 实现一个公共接口,或者从一个公共抽象基础继承 class。

例如:

public interface IMyInterface
{
    // ...
}

public class ClassX : IMyInterface
{
    // ...
}

public class ClassY : IMyInterface
{
    // ...
}

public class ClassZ : IMyInterface
{
    // ...
}

或:

public abstract class MyBaseClass
{
    // ...
}

public class ClassX : MyBaseClass
{
    // ...
}

public class ClassY : MyBaseClass
{
    // ...
}

public class ClassZ : MyBaseClass
{
    // ...
}

然后您可以将 GetData() 方法实现为 IEnumerable<IMyInterface>(或者 IEnumerable<MyBaseClass>,如果使用抽象基础 class 而不是接口)。

例如:

public static IEnumerable<IMyInterface> GetData(string id)
{
    if (id == "-string1" || id == "-all")
        yield return new ClassX();

    if (id == "-string2" || id == "-all")
        yield return new ClassY();

    if (id == "-string3" || id == "-all")
        yield return new ClassX();
}

您将在 foreach:

中使用
foreach (var item in GetData("-all"))
{
    // ...
}

如果您不想或不能使用公共基础 class 或接口,那么您将不得不 return 对象,声明 GetData() 为:

 public static IEnumerable<object> GetData(string id)

不过我看不出你这样做有什么意义。在使用它们之前,您可能必须知道 returned 类型是什么并进行相应的转换,这使得它们的使用极为不便。

像这样使用多态性(或接口,取决于您的实现)

 public baseX 
 {}

 public classX : baseX 
 {}

并将函数 return 值更改为 baseX 列表:

private list<baseX> GetData(string id)
{
   list<baseX> returnList = new list<baseX>();

   if (id == "-string1")
       return returnList.add( new class1(this, @"path") );
   if (id == "-string2")
       return returnList.add( new class2(this, @"path") );
   if (id == "-string3")
       return returnList.add( new class3(this, @"path") );

   // ...

   if (id == "-All")
   {
       returnList.add( new class1(this, @"path") );
       returnList.add( new class2(this, @"path") );
       returnList.add( new class3(this, @"path") );
       // .....
   }

   return returnList;
}