Type.InvokeMember 似乎不适用于 short,int16 或其他 16 位数字类型的类


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+ 数字类型,它可以工作

调用成员是否不支持 short,int16 等类型。或者我可能会更改另一种分配值的方式。

任何帮助不胜感激

你能试试这个吗? 它对我有用。

//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);

相关内容

最新更新