【问题标题】:It seems that Type.InvokeMember does not work with short,int16 or other 16bit numeric type of class似乎 Type.InvokeMember 不适用于 short、int16 或其他 16 位数字类型的类
【发布时间】:2017-07-13 03:48:34
【问题描述】:
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 等类型。或者我可能会改变另一种赋值方式。

感谢任何帮助

【问题讨论】:

  • 您将int 传递给InvokeMember() 方法。我确定您是否传递了正确类型的值,例如short,它会工作的。
  • 公共字符串 aPropery { get;放; } 是一个属性。公共字符串 aMember = "aValue";被称为成员或字段。
  • @PeterDuniho 是的,你是对的,我必须使用类型转换(短)2,以便 InvokeMember() 正常工作

标签: c# reflection invokemember


【解决方案1】:

请你试试这个。它对我有用。

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

【讨论】:

    猜你喜欢
    • 2023-01-05
    • 2015-08-15
    • 1970-01-01
    • 2014-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多