我有以下两种方法:
Method1(int a, int b)
{
var type = Typ1(a, b);
}
Method2
{
var type = Typ2(a, b);
}
我想写一个完成这项工作的通用方法:
GenericMethod<T>(int a, int b)
{
var type = new T(a, b);
}
但是T不接受任何输入参数。我怎么能做到这一点?
我知道使用Activator.Instance(T, a, b)
我可以做到这一点,但它的性能成本很高。
我也知道我可以使用T()然后设置属性来调用泛型类型的默认构造函数,但在我的情况下,我想传递2个必须的参数。
我不想引入没有参数的构造函数。
有没有办法用泛型做到这一点?
谢谢,
答案 0 :(得分:4)
创建工厂类:
public static class TypeFactory<T>
{
private static Func<int, int, T> Func { get; set; }
static TypeFactory()
{
TypeFactory<Type1>.Func = (a, b) => new Type1(a, b);
TypeFactory<Type2>.Func = (a, b) => new Type2(a, b);
}
public static T Create(int a, int b)
{
return Func(a, b);
}
}
然后像这样使用它:
var type1 = TypeFactory<Type1>.Create(1, 2);
var type2 = TypeFactory<Type2>.Create(1, 2);
答案 1 :(得分:2)
没有
相反,您可以接受为您创建它们的委托:
GenericMethod<T>(int a, int b, Func<int, int, T> creator) {
T t = creator(a, b);
}
GenericMethod(8, 9, (a, b) => new YourType(a, b));
你也可以store these creators in a generic static class:
static class Creator<T> {
public static Func<int, int, T> Func { get; set; }
}
GenericMethod<T>(int a, int b) {
T t = Creator<T>.Func(a, b);
}
Creator<YourType>.Func = (a, b) => new YourType(a, b);
答案 2 :(得分:2)
如果您不想使用Activator,可以使用表达式树。 Incorrect number of parameters supplied for lambda declaration
答案 3 :(得分:0)
理论上,您需要使用generic type constraint。但是,唯一可用的构造函数约束是对无参数构造函数where T : new()
的支持。
如果Typ1
和Typ2
共享一个使用2个整数定义属性的基类,或者两者都支持保证这些整数的setter的接口,则可以在每个类上定义无参数构造函数并使用其他约束以后允许访问这些属性。
答案 4 :(得分:0)
public static class MyTypeFactory
{
static MyTypeFactory()
{
MethodRunner<Type1>.Func = (a, b) => new Type1(a, b);
MethodRunner<Type2>.Func = (a, b) => new Type2(a, b);
}
public static T Create<T>(int a, int b)
{
return MethodRunner<T>.Func(a, b);
}
static class MethodRunner<T>
{
public static Func<int, int, T> Func { get; set; }
}
}
这看起来很有前途?!
是静态ctor线程安全的本质(CLR),如静态字段初始化器?