in c#, is it possible to access the common protected fields of one child in another child class?
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 开发者_StackOverflowto hide this field from outside (classes not derived from commonParent) while leaving it accessible within the scope of commonParent and its children.
Read following blog post by Eric Lippert,
- Why Can't I Access A Protected Member From A Derived Class?
try to use protected internal
it will work
you have to declare it at least protected
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:
class commonParent
{
protected string name;
protected static string GetName(commonParent other)
{
return other.name;
}
}
class child1 : commonParent
{
// do some stuff
}
class child2 : commonParent
{
protected void test()
{
child1 myChild1 = new child1();
string oldName = commonParent.GetName(myChild1);
}
}
This has the benefit of providing access to protected data only to derived classes.
精彩评论