简体   繁体   English

根据参数返回类型的C#函数

[英]C# function that returns type according to a parameter

I would like to create a function that returns new object according to the parameter, for example: 我想创建一个根据参数返回新对象的函数,例如:

Base Class: 基类:

class BaseClass
{
    public int x;
}

Class One: 第一类:

class TestClassOne: BaseClass
{        
    public TestClassOne()
    {
        this.x = 1;
    }   
}

Class Two: 第二课:

class TestClassTwo: BaseClass
{
    public TestClassOne()
    {
        this.x = 2;
    }   
}

Main: 主要:

static void Main(string[] args)
{
    BaseClass bc = GetConstructor("TestClassOne");
    Console.WriteLine(bc.x); //Prints 1
}

static BaseClass GetConstructor(string className)
{
    if(className.Equals("TestClassOne"))
    {
        return new TestClassOne();
    }
    else if(className.Equals("TestClassTwo"))
    {
        return new TestClassTwo();
    }
    return null;
} 

The code I wrote works well, the problem is when I will have a lot of derived classes like TestClassThree, TestClassFour... TestClassThousand. 我编写的代码运行良好,问题是当我将拥有许多派生类(如TestClassThree,TestClassFour ... TestClassThousand)时。 How can I make a function that returns the correct constructor without if else or switch case and etc? 我如何制作一个返回正确构造函数的函数,而无需if if else或switch case等? I think that reflection would be a good option but I'm not really sure how to use it. 我认为反射将是一个不错的选择,但我不确定如何使用它。 Thanks! 谢谢!

It would be best if you can use a generic method, lik in the answer of René, but you are using strings, so it doesn't seem so. 最好是可以使用通用方法,例如在René的答案中,但是您使用的是字符串,所以事实并非如此。

There are two steps: 分两个步骤:

  • Get the correct type; 获取正确的类型;
  • Create an instance. 创建一个实例。

This is the minimal code necessary: 这是必需的最少代码:

Type t = Assembly.GetExecutingAssembly().GetType("SO.BaseClass");

object o = Activator.CreateInstance(t);

As you can see, you need to know the assembly and the namespace of the type, or you will have to do some fuzzy matching on either. 如您所见,您需要知道类型的程序集和名称空间,否则您将必须对两者进行模糊匹配。

I would offer a word of caution with your implementation. 对于您的实施情况,我会提请注意。 What you are attempting to do is called a factory. 您试图做的事情叫做工厂。 Considering the fact that you are adding a dependency for a base class, you will be limited to only allowing constructors with that base class. 考虑到要为基类添加依赖项这一事实,您将被限制为仅允许具有该基类的构造函数。 If you ever needed certain classes to have a different base class but be offered through the same method, you would need to share an interface instead. 如果曾经需要某些类具有不同的基类,但是通过相同的方法提供,则需要共享一个接口。 Like others have suggested, you can use generics. 就像其他人建议的那样,您可以使用泛型。 Here is an example without generics: 这是一个没有泛型的示例:

public static IMyInterface GetMatchingClass(string className)
    {
        Type t = Type.GetType(className);
        return (IMyInterface)Activator.CreateInstance(t);
    }

As long as the classes you return implement the given interface, all is peachy. 只要您返回的类都实现给定的接口,一切都是桃红色的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM