我想要做的是自动创建一些对象。
在Java中,可以将类作为参数传递,例如
Class A{
}
Object createObjectBy(class clazz){
// .. do construction work here
}
when using it, just ---> createObjectBy(A.class)
它对很多事情都有好处。
那么,在C#中我该如何做类似的事情呢?
我想要做的是自动创建一些对象。
在Java中,可以将类作为参数传递,例如
Class A{
}
Object createObjectBy(class clazz){
// .. do construction work here
}
when using it, just ---> createObjectBy(A.class)
它对很多事情都有好处。
那么,在C#中我该如何做类似的事情呢?
Object createObjectBy(Type clazz){
// .. do construction work here
Object theObject = Activator.CreateInstance(clazz);
return theObject;
}
使用方法:
createObjectBy(typeof(A));
或者你可以直接使用Activator.CreateInstance
:-)
最理想的方式是使用泛型。
public static T CreateInstance<T>() where T: new()
{
// Do some business logic
Logger.LogObjectCreation(typeof(T));
// Actualy instanciate the object
return new T();
}
var employee = CreateInstance<Employee>();
如果对象的类型在运行时未知,例如通过插件系统,您需要使用Type
类:
public static object CreateInstance(Type type)
{
// Do some business logic
Logger.LogObjectCreation(type);
// Actualy instanciate the object
return Activator.CreateInstance(type);
}
var instance = CreateInstance(someType);
当然,使用关键字new
实例化一个对象是最快的方法。除非你可以通过缓存来重用对象,而不需要实例化。
如果你只能接受第二种类型未知的方法,则有一些替代方案来替换Activator.CreateInstance
。虽然该文章建议使用lambda表达式,但你应该考虑以下因素:
如果你只需创建对象一次,请继续使用Activator.CreateInstance方法。如果你需要在短时间内多次创建对象,请尝试使用lambda表达式的方法。最后一种方法类似于编译正则表达式与即时正则表达式之间的区别。
obj.GetType();
或者没有对象实例
typeof(className);
C#不支持这个。但是你想做什么?
你可能可以使用:
createObjectBy(Type type);
或者
createObjectBy<T>();