我正在尝试构建一个使用C#的泛型功能的工厂方法.
在这个工厂方法中,我想将它约束到一些特定的类,所有这些类都没有默认的构造函数.
这是我的例子.有人能告诉我是否可以运行它?
public class AbstractClass {
//this abstract class does not have a default constructor, nor its subclasses
public AbstractClass(SomeClassName obj) {
//use obj for initialization
}
}
//this factory class should create objects of type T that inherit
//from AbstractClass and invoke the non-default constructor
public class FactoryClass {
public static T BuildObject<T> (SomeClassName obj) where T: AbstractClass {
return new T(obj); //does not work?!?!?!
}
}
//Edit: ANSWER!!!
public static T BuildObject<T>(SomeClassUsedForTheConstructor item) where T : SomeAbstractClass {
return (T) Activator.CreateInstance(typeof (T), item);
}
Run Code Online (Sandbox Code Playgroud)
查看Type类和 GetConstructor。获取 ConstructorInfo 对象后,使用 Invoke 方法。
var x = typeof(T);
var t = x.GetConstructor(new[] {obj.GetType()});
object u = t.Invoke(<inputs>);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1426 次 |
| 最近记录: |