It seems that Type.InvokeMember does not work with short,int16 or other 16bit numeric type of class

75 Views Asked by At
public class Test{
    public string name{get;set}
    public short age{get;set;}
}

....

var type = typeof(Test);

var ins = Activator.CreateInstance(type);

type.InvokeMember("name", BindingFlags.DeclaredOnly |
                    BindingFlags.Public | BindingFlags.NonPublic |
                    BindingFlags.Instance | BindingFlags.SetProperty, null,   ins ,new object[] { "alibaba" });

type.InvokeMember("age", BindingFlags.DeclaredOnly |
                    BindingFlags.Public | BindingFlags.NonPublic |
                    BindingFlags.Instance | BindingFlags.SetProperty | BindingFlags.SetField | BindingFlags.SuppressChangeType, null, ins ,new object[] { 2 });

...

An exception of method 'age' not found throw when running,if I change the type of 'age' to int or other 32+ numeric type, it works

Whether or not the InvokeMember does not support type of short,int16 ect. Or I might change another way to assign value.

Any help is appreciated

1

There are 1 best solutions below

0
On BEST ANSWER

Can you please try this. It worked for me.

//credit to stack overflow post and the following post
//https://stackoverflow.com/questions/1089123/setting-a-property-by-reflection-with-a-string-value

Test test = new Test();
PropertyInfo property = typeof(Test).GetProperty("name");
property.SetValue(test, "NameValue", null);
PropertyInfo propertyTwo = typeof(Test).GetProperty("age");
short aShort = 49;
propertyTwo.SetValue(test, aShort, null);