访问类保护字段而不修改原始类 [英] Accessing a class protected field without modifying original class
本文介绍了访问类保护字段而不修改原始类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用一些公开某种类型(由方法返回)的第三方库.
I am using some 3rd party library that exposes some type (returned by a method).
此类型具有一些我感兴趣的受保护字段,但是由于其可见性受保护,因此我无法使用它们.
This type has some protected fields i am interested in, however i am not able to use them since their visibility is protected.
这是问题的简化:
public class A
{
protected object Something;
public A Load()
{
return new A();
}
}
public class ExtendedA : A
{
public void DoSomething()
{
// Get an instance.
var a = Load();
// Access protected fields (doesn't compile).
a.Something = ....
}
}
有什么简单的方法可以实现这一目标吗?
Is there any easy way to achieve this?
推荐答案
说明
您可以使用this.Something
访问该字段,因为您的课程是从class A
派生的.
Description
You can access the Field using this.Something
because your class is derived from class A
.
如果要创建class A
的实例而不是派生类,则只能使用反射来访问该字段.
If you want to create a instance of the class A
, not your derived class, you can only access the field using reflection.
public class ExtendedA : A
{
public void DoSomething()
{
// Get an instance.
var a = Load();
//get the type of the class
Type type = a.GetType();
BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic;
// get the field info
FieldInfo finfo = type.GetField("Something", bindingFlags);
// set the value
finfo.SetValue(a, "Hello World!");
// get the value
object someThingField = finfo.GetValue(a);
}
}
更多信息
- 通过反射访问受保护的属性和字段
- Accessing Protected Properties and Fields with Reflection
More Information
这篇关于访问类保护字段而不修改原始类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文