C#Reflection - 转换私有Object字段

时间:2010-03-30 22:09:59

标签: c# reflection object private casting

我有以下课程:

public class MyEventArgs : EventArgs
{
    public object State;

    public MyEventArgs (object state)
    {
        this.State = state;
    }

}

public class MyClass
{
     // ...

     public List<string> ErrorMessages 
     {
          get
          {
               return errorMessages;
          }
      }
}

当我举起事件时,我将MyEventArgs对象的“State”设置为MyClass类型的对象。我正在尝试通过事件处理程序中的反射检索ErrorMessages:

 public static void OnEventEnded(object sender, EventArgs args)
 {
      Type type = args.GetType();
      FieldInfo stateInfo = type.GetField("State");
      PropertyInfo errorMessagesInfo = stateInfo.FieldType.GetProperty("ErrorMessages");

      object errorMessages = errorMessagesInfo.GetValue(null, null);

  }

但是这会将errorMessagesInfo返回为null(即使stateInfo不为null)。是否可以检索ErrorMessages?

编辑:我应该澄清事件处理程序在不同的程序集中,我不能引用第一个程序集(包含MyEventArgs和MyClass)来构建问题。

谢谢

修改:解决方案

FieldInfo stateInfo = args.GetType().GetField("State");
Object myClassObj = stateInfo.GetValue(args);
PropertyInfo errorMessagesInfo = myClassObj.GetType().GetProperty("ErrorMessages");
object errorMessagesObj = errorMessagesInfo.GetValue(myClassObj, null);
IList errorMessages = errorMessagesObj as IList;

4 个答案:

答案 0 :(得分:2)

您不需要对此进行反思,只需将EventArgs投射到MyEventArgs,然后您就可以访问ErrorMessages媒体资源了:

 public static void OnEventEnded(object sender, EventArgs args) 
 { 
     MyEventArgs myArgs = (MyEventArgs)args;
     MyClass detail = (MyClass)myArgs.State;

     // now you can access ErrorMessages easily...
     detail.ErrorMessages....
 } 

您应该避免对其类型完全已知的内容使用反射。您应该使用类型转换将引用转换为您期望的类型。当类型信息是动态的,或者在编译时在代码中不可用时,反射是有意义的(似乎不是这种情况)。

答案 1 :(得分:1)

一个例子......

PropertyInfo inf = ctl.GetType().GetProperty("Value");
errorMessagesInfo.GetValue(ClassInstance, null);




//And to set a value
    string value = reader[campos[i]].ToString();
    inf.SetValue(ctl, value, null);

答案 2 :(得分:0)

您需要传递MyClass的实例:

errorMessagesInfo.GetValue(someInstanceOfMyClass, null);

如果发件人的类型为MyClass,则表示:

errorMessagesInfo.GetValue(sender, null);

答案 3 :(得分:0)

解决方案:

FieldInfo stateInfo = args.GetType().GetField("State");
Object myClassObj = stateInfo.GetValue(args);
PropertyInfo errorMessagesInfo = myClassObj.GetType().GetProperty("ErrorMessages");
object errorMessagesObj = errorMessagesInfo.GetValue(myClassObj, null);
IList errorMessages = errorMessagesObj as IList;