在c#中返回多个类

0 c# loops 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;
}
Run Code Online (Sandbox Code Playgroud)

问题是,我希望有一个条件(例如"-all")逐个返回每个类.我不知道该怎么做.有没有办法逐一归还这些课程?因为我知道它不能与'return'一起使用,因为它结束了代码,所以其余部分无法访问.

Mat*_*son 5

首先,如果可能,您应该使所有类实现公共接口,或者从公共抽象基类继承.

例如:

public interface IMyInterface
{
    // ...
}

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

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

public class ClassZ : IMyInterface
{
    // ...
}
Run Code Online (Sandbox Code Playgroud)

要么:

public abstract class MyBaseClass
{
    // ...
}

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

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

public class ClassZ : MyBaseClass
{
    // ...
}
Run Code Online (Sandbox Code Playgroud)

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

例如:

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();
}
Run Code Online (Sandbox Code Playgroud)

您将使用哪一个foreach:

foreach (var item in GetData("-all"))
{
    // ...
}
Run Code Online (Sandbox Code Playgroud)

如果您不想或不能使用公共基类或接口,则必须通过声明GetData()为:返回对象:

 public static IEnumerable<object> GetData(string id)
Run Code Online (Sandbox Code Playgroud)

我不明白你这样做的重点.在使用它们之前,您可能必须知道返回的类型是什么并进行相应的转换,这使得使用它们非常不方便.