[英]How to access a private base class field using Reflection
I'm trying to set the private "visible" field on a variable of type BaseClass. 我正在尝试在BaseClass类型的变量上设置私有的“可见”字段。
I've successfully accessed the variable of type ChildClass, and the FieldInfo for the "visible" field on the BaseClass. 我已经成功访问了ChildClass类型的变量,以及BaseClass上“ visible”字段的FieldInfo。
But when I try to set/get the value of the field, I get the error System.Runtime.Remoting.RemotingException: Remoting cannot find field 'visible' on type 'BaseClass'. 但是,当我尝试设置/获取字段的值时,出现错误System.Runtime.Remoting.RemotingException:远程处理无法在类型'BaseClass'上找到字段'visible'。
So Is there a way to "down cast" a variable of type ChildClass to BaseClass in order for the reflection to work? 那么,是否有一种方法可以将“ ChildClass”类型的变量“强制转换”为BaseClass,以便进行反射?
Edit: The exact code I'm using: 编辑:我正在使用的确切代码:
// get the varible
PropertyInfo pi = overwin.GetProperty("Subject", BindingFlags.Instance|BindingFlags.Public);
CalcScene scene = (CalcScene) pi.GetValue(inwin, null);
// <<< scene IS ACTUALLY A TYPE OF DisplayScene, WHICH INHERITS FROM CalcScene
// get the 'visible' field
Type calScene = typeof(CalcScene);
FieldInfo calVisible = calScene.GetField("visible",BindingFlags.Instance|BindingFlags.NonPublic);
// set the value
calVisible.SetValue(scene, true); // <<< CANNOT FIND FIELD AT THIS POINT
The exact class structure: 确切的类结构:
class CalcScene
{
private bool visible;
}
class DisplayScene : CalcScene
{
}
you can try like this 你可以这样尝试
class B
{
public int MyProperty { get; set; }
}
class C : B
{
public string MyProperty2 { get; set; }
}
static void Main(string[] args)
{
PropertyInfo[] info = new C().GetType().GetProperties();
foreach (PropertyInfo pi in info)
{
Console.WriteLine(pi.Name);
}
}
produces 产生
MyProperty2 MyProperty
Here is some code that demonstrates the difference between getting a field vs a property: 以下是一些代码,演示了获取字段与属性之间的区别:
public static MemberInfo GetPropertyOrField(this Type type, string propertyOrField)
{
MemberInfo member = type.GetProperty(propertyOrField, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
if (member == null)
member = type.GetField(propertyOrField, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
Debug.Assert(member != null);
return member;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.