![](/img/trans.png)
[英]Can I use PrivateObject class or Reflection to access a field in a private class?
[英]How to access a private base class field using Reflection
我正在尝试在BaseClass类型的变量上设置私有的“可见”字段。
我已经成功访问了ChildClass类型的变量,以及BaseClass上“ visible”字段的FieldInfo。
但是,当我尝试设置/获取字段的值时,出现错误System.Runtime.Remoting.RemotingException:远程处理无法在类型'BaseClass'上找到字段'visible'。
那么,是否有一种方法可以将“ ChildClass”类型的变量“强制转换”为BaseClass,以便进行反射?
编辑:我正在使用的确切代码:
// 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
确切的类结构:
class CalcScene
{
private bool visible;
}
class DisplayScene : CalcScene
{
}
你可以这样尝试
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);
}
}
产生
MyProperty2 MyProperty
以下是一些代码,演示了获取字段与属性之间的区别:
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.