Type.InvokeMember 似乎不适用于 class 的 short、int16 或其他 16 位数字类型
It seems that Type.InvokeMember does not work with short,int16 or other 16bit numeric type of class
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 });
...
当 运行 时未找到方法 'age' 的异常抛出,如果我将 'age' 的类型更改为 int 或其他 32+ 数字类型,它将起作用
InvokeMember是否不支持short,int16等类型。或者我可能会改变另一种赋值方式。
感谢任何帮助
你能试试这个吗?它对我有用。
//credit to stack overflow post and the following post
//
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);
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 });
...
当 运行 时未找到方法 'age' 的异常抛出,如果我将 'age' 的类型更改为 int 或其他 32+ 数字类型,它将起作用
InvokeMember是否不支持short,int16等类型。或者我可能会改变另一种赋值方式。
感谢任何帮助
你能试试这个吗?它对我有用。
//credit to stack overflow post and the following post
//
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);