C# 中是否有带参数约束的泛型构造函数? [英] Is there a generic constructor with parameter constraint in C#?
本文介绍了C# 中是否有带参数约束的泛型构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 C# 中,您可以对泛型方法施加约束,例如:
In C# you can put a constraint on a generic method like:
public class A {
public static void Method<T> (T a) where T : new() {
//...do something...
}
}
在您指定 T
应该有一个不需要参数的构造函数的地方.我想知道是否有办法添加约束,例如存在带有 float[,]
参数的构造函数?"
Where you specify that T
should have a constructor that requires no parameters. I'm wondering whether there is a way to add a constraint like "there exists a constructor with a float[,]
parameter?"
以下代码无法编译:
public class A {
public static void Method<T> (T a) where T : new(float[,] u) {
//...do something...
}
}
解决方法也有用吗?
推荐答案
正如你所发现的,你不能这样做.
As you've found, you can't do this.
作为一种解决方法,我通常提供一个可以创建 T
类型对象的委托:
As a workaround I normally supply a delegate that can create objects of type T
:
public class A {
public static void Method<T> (T a, Func<float[,], T> creator) {
//...do something...
}
}
这篇关于C# 中是否有带参数约束的泛型构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文