在c#中,是否可以访问另一个子类中一个子类的公共受保护字段?
请参阅代码中的问题:
class commonParent {
protected string name;
}
class child1:commonParent{
// do some stuff
}
class child2:commonParent{
// do some stuff
protected void test(){
child1 myChild1 = new child1();
//is it possible to access myChild1.name in child2 without
//declaring the name public or internal?
// I want to do something like this:
string oldName = myChild1.name;
//but I got the error:
//Error 46 Cannot access protected member 'commonParent.name'
//via a qualifier of type 'child1'; the qualifier must be of
//type 'child2' (or derived from it)
}
}
字段“name”仅由 commonParent 类的所有子级使用。我想从外部隐藏此字段(不是从 commonParent 派生的类),同时使其在 commonParent 及其子项的范围内可访问。
See the question in code:
class commonParent {
protected string name;
}
class child1:commonParent{
// do some stuff
}
class child2:commonParent{
// do some stuff
protected void test(){
child1 myChild1 = new child1();
//is it possible to access myChild1.name in child2 without
//declaring the name public or internal?
// I want to do something like this:
string oldName = myChild1.name;
//but I got the error:
//Error 46 Cannot access protected member 'commonParent.name'
//via a qualifier of type 'child1'; the qualifier must be of
//type 'child2' (or derived from it)
}
}
The field "name" is only used by all children of commonParent class. I want to hide this field from outside (classes not derived from commonParent) while leaving it accessible within the scope of commonParent and its children.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
请阅读 Eric Lippert 撰写的以下博客文章,
尝试使用
受保护的内部
它会起作用Read following blog post by Eric Lippert,
try to use
protected internal
it will work你必须声明它至少是受保护的
you have to declare it at least protected
我认为这是糟糕的设计,您应该将 Name 声明为 Private 并使用 Get、Set 访问器创建一个属性,您可以在其中选择 Get 或 Set 是否可以是 Public、Private 或 Protected,否则 Protected 将允许同一命名空间的任何类访问 Field 或 Property 。
I think this is bad design ,you should declare Name as Private and create a property with Get,Set accessors ,where you can chose if Get or Set could be Public ,Private or Protected ,otherwise Protected will allow any classes of the Same namespace to access a Field or Property .
要回答您的问题,您可以使用反射来访问它们。但这不是您想要依赖的东西。
To answer your question, you can access them using reflection. This is not something you want to rely on, though.
我的方法是提供一个受保护的静态方法,该方法确实可以访问受保护的值,但仅适用于派生类,如下面的代码所示:
这样做的好处是仅向派生类提供对受保护数据的访问。
My approach to this is to provide a protected static method that does have access to the protected value, but is only available to the derived classes, like in the code below:
This has the benefit of providing access to protected data only to derived classes.