Emulating delegates with free generic type parameters in C#

前端 未结 3 716
小鲜肉
小鲜肉 2020-12-16 20:31

This is a hard question about language design, patterns and semantics. Please, don\'t down-vote just because you don\'t see the practical value.

3条回答
  •  悲哀的现实
    2020-12-16 21:19

    This does actually not make sense under .Net's type system.

    What you're describing is a type constructor – a "function" that takes one or more types and returns a concrete (parameterized, or closed) type.

    The problem is that type constructors themselves are not types. You cannot have an object or variable of an open type; type constructors can only be used to generate concrete types.

    In other words, there is no way to represent a reference to an open function within .Net's type system.


    The best you can do is to use reflection; a MethodInfo can describe an open generic method.
    You can get a compile-time type-safe reference to an open MethodInfo by writing a generic method that takes an expression tree with a fake generic parameter:

    public MethodInfo GetMethod(Expression method) {
        //Find the MethodInfo and remove all TPlaceholder parameters
    }
    
    GetMethod(() => SomeMethod(...));
    

    The TPlaceholder parameter is necessary in case you want to reference an open generic method with a constraint on that parameter; you can pick a placeholder type that meets the constraint.

提交回复
热议问题