How can I constrain generic parameter to have a certain static function?
I want to h开发者_JAVA百科ave a generic parameter which implement certain 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. 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. 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.
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.
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.
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. I would love to have this feature as well. :)
精彩评论