Generic constructors and reflection

前端 未结 4 1026
说谎
说谎 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:55

    You want System.Reflection.ParameterInfo.ParameterType.IsGenericParameter. Here's a VS2008 unit test that passes that illustrates this:

    Class:

    public class Foo
    {
        public Foo(T val)
        {
            this.Value = val.ToString();
        }
        public Foo(string val)
        {
            this.Value = "--" + val + "--";
        }
    
        public string Value { get; set; }
    }
    

    Test method:

    Foo f = new Foo("hello");
    Assert.AreEqual("--hello--", f.Value);
    
    Foo g = new Foo(10);
    Assert.AreEqual("10", g.Value);
    
    Type t = typeof(Foo);
    t = t.GetGenericTypeDefinition();
    
    Assert.AreEqual(2, t.GetConstructors().Length);
    
    System.Reflection.ConstructorInfo c = t.GetConstructors()[0];
    System.Reflection.ParameterInfo[] parms = c.GetParameters();
    Assert.AreEqual(1, parms.Length);
    Assert.IsTrue(parms[0].ParameterType.IsGenericParameter);
    
    c = t.GetConstructors()[1];
    parms = c.GetParameters();
    Assert.AreEqual(1, parms.Length);
    Assert.IsFalse(parms[0].ParameterType.IsGenericParameter);
    

    The notable point here is the parms[0].ParameterType.IsGenericParameter check which checks if the parameter is a generic or not.

    Once you've found your constructor then you've got the ConstructorInfo to pass to Emit.

    public System.Reflection.ConstructorInfo FindStringConstructor(Type t)
    {
        Type t2 = t.GetGenericTypeDefinition();
    
        System.Reflection.ConstructorInfo[] cs = t2.GetConstructors();
        for (int i = 0; i < cs.Length; i++)
        {
            if (cs[i].GetParameters()[0].ParameterType == typeof(string))
            {
                return t.GetConstructors()[i];
            }
        }
    
        return null;
    }
    

    Not exactly sure what your intention is though.

提交回复
热议问题