在C#中,您可以对泛型方法施加约束,如下所示:
public class A {
public static void Method<T> (T a) where T : new() {
//...do something...
}
}
其中指定T
应该有一个不需要参数的构造函数。我想知道是否有办法添加类似“存在一个带有float[,]
参数的构造函数?”这样的约束。
以下代码无法编译:
public class A {
public static void Method<T> (T a) where T : new(float[,] u) {
//...do something...
}
}
解决方法也是有用的吗?
发布于 2009-12-06 01:41:00
正如您所发现的,您不能这样做。
作为一种解决办法,我通常提供一个可以创建T
类型的对象的委托
public class A {
public static void Method<T> (T a, Func<float[,], T> creator) {
//...do something...
}
}
发布于 2012-03-26 16:13:13
使用反射创建泛型对象时,类型仍然需要声明正确的构造函数,否则将抛出异常。您可以传入任何参数,只要它们与其中一个构造函数匹配。
使用这种方法,您不能在模板中对构造函数施加约束。如果构造函数丢失,则需要在运行时处理异常,而不是在编译时获得错误。
// public static object CreateInstance(Type type, params object[] args);
// Example 1
T t = (T)Activator.CreateInstance(typeof(T));
// Example 2
T t = (T)Activator.CreateInstance(typeof(T), arg0, arg1, arg2, ...);
// Example 3
T t = (T)Activator.CreateInstance(typeof(T), (string)arg0, (int)arg1, (bool)arg2);
发布于 2009-12-06 01:40:09
我使用lambda方法解决这个问题。
public static void Method<T>(Func<int,T> del) {
var t = del(42);
}
用例
Method(x => new Foo(x));
https://stackoverflow.com/questions/1852837
复制相似问题