[英]Generic constraint: Enforce type to have static function and constructor with parameters
I know you can write: 我知道你可以写:
class GenericClass<T> where T : new()
{
}
to enforce that T
has an empty constructor. 强制执行
T
有一个空构造函数。
My Qs are : 我的Qs是:
can you enforce that T
has a constructor with a specific type of parameter? 你能强制说
T
有一个具有特定参数类型的构造函数吗? Like: 喜欢:
class SingletonFactoryWithEmptyConstructor<T> where T : new(int)
can you enforce that T
has a static function (let's say, void F()
) so that you can use this function inside the generic class? 你能强制执行
T
有一个静态函数(比方说, void F()
),这样你就可以在泛型类中使用这个函数吗? Like : 喜欢 :
class GenericClass<T> where T : void F() { void G () { TF(); } }
I know you can specify that T
implements an interface but I don't want that. 我知道你可以指定
T
实现一个接口,但我不希望这样。 I want to specify that T
has a static function. 我想指定
T
具有静态函数。
No, there's nothing like this in C#. 不,在C#中没有这样的东西。
I've previously suggested that "static interfaces" could express this reasonably neatly. 我之前曾建议“静态接口”可以合理地表达这一点。 They'd only be useful for generic type constraints (I suspect, anyway) but then you could express:
它们只对泛型类型约束有用(我怀疑,无论如何)但是你可以表达:
The last of these points is particularly interesting in my view, allowing things like a generic "Average" method over numeric types with suitable addition and division operators. 在我看来,这些要点中的最后一点特别有趣,允许使用具有合适的加法和除法运算符的数字类型的通用“平均”方法。
I believe some folks at MS have thought about something similar, but I haven't heard anything to suggest they're actively working on it. 我相信MS的一些人已经考虑过类似的东西,但我没有听到任何暗示他们正在积极研究的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.