如何在C#中使用类名作为参数

joj*_*ojo 39 c#

我想要做的是自动创建一些对象.

例如,在Java中,类可以作为参数传递

Class A{

}


Object createObjectBy(class clazz){
       // .. do construction work here
}

when using it, just ---> createObjectBy(A.class)
Run Code Online (Sandbox Code Playgroud)

这对很多事情都有好处.

所以,我怎么能在C#做类似的事情?

Avi*_* P. 47

Object createObjectBy(Type clazz){
   // .. do construction work here
    Object theObject = Activator.CreateInstance(clazz);
    return theObject;
}
Run Code Online (Sandbox Code Playgroud)

用法:

createObjectBy(typeof(A));
Run Code Online (Sandbox Code Playgroud)

或者你可以直接使用Activator.CreateInstance:-)

  • 如果类型没有无参数构造函数,这将失败 (3认同)

Pie*_*ant 38

理想的方法是使用泛型

类型在设计时已知

public static T CreateInstance<T>() where T: new()
{
    // Do some business logic
    Logger.LogObjectCreation(typeof(T));

    // Actualy instanciate the object
    return new T();
}
Run Code Online (Sandbox Code Playgroud)

一个电话示例看起来像

var employee = CreateInstance<Employee>();
Run Code Online (Sandbox Code Playgroud)

类型在运行时未知

如果对象的类型在运行时是未知的,例如通过插件系统,则需要使用以下Type类:

public static object CreateInstance(Type type)
{
    // Do some business logic
    Logger.LogObjectCreation(type);

    // Actualy instanciate the object
    return Activator.CreateInstance(type);
}
Run Code Online (Sandbox Code Playgroud)

一个电话示例看起来像

var instance = CreateInstance(someType);
Run Code Online (Sandbox Code Playgroud)

性能

当然,除了使用关键字之外,没有什么比实例化对象更好new.除了可能不是实例化,而是重用一个对象,比如通过缓存.

如果你不得不接受第二种类型未知的方法,那么有一些替代方法Activator.CreateInstance.虽然文章推荐使用lambda表达式,但您最大的考虑因素是:

  • 您的未知对象是否需要在短时间内实例化,或者您只创建一次

如果您只需要创建一次对象,只需坚持使用Activator.CreateInstance方法即可.如果您需要在短时间内多次创建它,请尝试lambda方法.最后一种方法类似于编译的正则表达式与即时正则表达式.


CAR*_*OTH 6

使用类Type.您可以通过调用返回它的实例

obj.GetType();
Run Code Online (Sandbox Code Playgroud)

或没有对象实例

typeof(className);
Run Code Online (Sandbox Code Playgroud)

我希望它有所帮助.


hac*_*sid 5

C#不支持此功能。但是你想做什么?

您可能可以使用:

createObjectBy(Type type);
Run Code Online (Sandbox Code Playgroud)

要么

createObjectBy<T>();
Run Code Online (Sandbox Code Playgroud)