[英]How can I constrain generic parameter to have a certain static function?
I want to have a generic parameter which implement certain static function.我想要一个通用参数来实现某些 static function。 As a part of its interface(teh static function) for me it is logical to have such generic parameter constrain, but I cannot find how to do this.作为其接口的一部分(static 函数)对我来说,拥有这样的通用参数约束是合乎逻辑的,但我找不到如何做到这一点。 Any help is appreciated.任何帮助表示赞赏。
Currently I'm fixing such problems by defining NOT static properties which returns static values, which as OOP developer I certainly don't like.目前我正在通过定义 NOT static 属性来解决此类问题,该属性返回 static 值,作为 OOP 开发人员我当然不喜欢。 This properties are part of some interface and the generic param is constraint to inherit from the interface.此属性是某些接口的一部分,通用参数是从接口继承的约束。
You can't - there's no such thing as constraining a type parameter by static members, unless you count the new()
constraint which requires a parameterless constructor.你不能 - 没有像 static 成员约束类型参数这样的事情,除非你计算需要无参数构造函数的new()
约束。
Note that static members can't be part of an interface in the normal C# sense of the word - even though they can obviously be part of the public API of the type.请注意,static 成员不能成为正常 C# 意义上的接口的一部分 - 即使它们显然可以是该类型的公共 API 的一部分。
I've previously blogged about the possibility of "static interfaces" in a future version of C# (just as a sort of feature request) but it's definitely not available now.我之前在博客上写过 C#未来版本中“静态接口”的可能性(只是作为一种功能请求),但现在绝对不可用。
Sometimes the best alternative is to have a separate type implementing a normal interface - if you can give us more information about your context, we may be able to suggest alternative approaches.有时最好的选择是让一个单独的类型实现一个普通的接口——如果你能给我们更多关于你的上下文的信息,我们也许可以建议替代方法。
At this time, it is not possible to have a constraint in C# like the one you require.此时,不可能像您需要的那样在 C# 中有约束。 I would love to have this feature as well.我也很想拥有这个功能。 :) :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.