![](/img/trans.png)
[英]C# - Casting a Reflection.PropertyInfo object to its Type
[英]C# Reflection - Casting private Object field
我有以下课程:
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对象的“状态”设置为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;
您不需要为此进行反射 ,只需将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....
}
您应该避免对反射类型完全了解的东西使用反射。 相反,您应该使用类型转换将引用转换为所需的类型。 当类型信息是动态的,或者在代码编译时不可用时,反射是有意义的(事实并非如此)。
一个例子....
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);
您需要传递MyClass的实例:
errorMessagesInfo.GetValue(someInstanceOfMyClass, null);
如果发送者是MyClass类型,则表示:
errorMessagesInfo.GetValue(sender, null);
解:
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.