简体   繁体   中英

Are F#'s generic member constraints possible within C#?

F# allows constraining generic types on the type's members, similar to:

    type ClassWithMemberConstraint<'T when 'T : (static member StaticProperty : unit)> =
    class end

This can be very handy, especially since the CLR doesn't allow defining interfaces with static members. Because F# allows such a constraint, I'm guessing it means that the CLR allows for generic member constraints as well, but from what I can tell, this isn't possible in C#.

Are there any ways to express this behavior in C#?

Because F# allows such a constraint, I'm guessing it means that the CLR allows for generic member constraints as well

Unfortunately, no. F# member constraints are implemented "outside of IL", so to speak. Functions with member constraints are not compiled into IL methods, but instead are stored in the F# metadata in the assembly. Then, every time such a function is called, its code is inlined at the call site with the generic type specialized to what is used in that particular place. That's why all functions with member constraints must be marked inline , by the way.

Well, comparing F# constraints with C# ones we can see that there are no equivalent of F# Explicit Member Constraint in C#.

What you possibly can do is define an abstract class and constrain on that, so your classes must inherit from that abstract class. Note, however, that the inherited classes will use the same static object of the parent abstract class.

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