Generic constructors and reflection

前端 未结 4 953
说谎
说谎 2021-02-14 17:25

Is it possible to see which constructor was the generic one?

internal class Foo
{
  public Foo( T value ) {}
  public Foo( string value ) {}
}

var cons         


        
4条回答
  •  醉酒成梦
    2021-02-14 17:29

    Slight clarification. Neither of the constructors are generic methods. They are normal methods on a generic class. For a method to be "generic" it must have a generic parameter . So doing a test like "IsGenericMethod" will return false.

    It's also not easy to simply look at the parameters and determine if they are generic. For the sample you gave it's possible to walk the arguments and look for a generic parameter. But also consider the following code

    public Foo(IEnumerable p1) ...
    public Foo(IEnumerable>> p1) ...
    

    You'll need to take items like this into account.

    EDIT

    The reason you're seeing all arguments as string is because you explicitly bound the type Foo before getting the constructors. Try switching your code to the following which uses an unbound Foo and hence will return generic parameters in the methods.

    var constructors = typeof( Foo<> ).GetConstructors();
    

提交回复
热议问题