简体   繁体   中英

How can I constrain generic parameter to have a certain static function?

I want to have 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. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM