问题
I am not able to access i in my derived class. m.i is not working. Why?
public class MyClass
{
protected int i;
public MyClass()
{
}
public virtual void Display()
{
Console.WriteLine("Base dis");
}
}
public class MyCla : MyClass
{
public MyCla()
{
}
int ij = 12;
public new void Display()
{
MyClass m = new MyClass();
// m.i is inaccessible here
Console.WriteLine("Derived dis");
}
}
回答1:
That is because protected variables and properties are only available to derived classes, within the derived context (thus by referencing it with this), and to instances of the current class (so if m was MyCla it would have worked).
MyCla m = new MyCla();
int x = m.i;
An option is to make the field internal, or protected internal if you wish, which makes it available to all classes within the assembly.
Here is a compiling example.
回答2:
The "protected" keyword means that only a type and types that derive from that type can access the member.
You have a couple of options if you want to be able to access that member
- Make it public.
- Make it internal. This will allow any types to access the member within the same assembly (or other assemblies should you add friend's
Cheers!
回答3:
You can not get protected variables in child class, But that will be accessible in Child Class method or Constructor directly eg. base.i;
public class MyCla : MyClass
{
public MyCla()
{
base.i=100;
}
int ij = 12;
public new void Display()
{
MyClass m = new MyClass();
base.i=100; // Accessible
m.i = 100; // Not Accessible
Console.WriteLine("Derived dis");
}
}
if you want that variable accessible with object, than make it public.
public int i;
public MyClass()
{
}
public class MyCla : MyClass
{
public MyCla()
{
}
int ij = 12;
public new void Display()
{
MyClass m = new MyClass();
m.i = 100; // accessible
Console.WriteLine("Derived dis");
}
}
Thanks
回答4:
You are creating a new instance:
MyClass m = new MyClass();
This instance only allows you to interact with public members. Thus m.i is not working.
Inside your derived class MyCla class however you have access to the protected field.
e.g
public new void Display()
{
i = 1; //this will work
}
回答5:
You can access i from within the MyCla class but in your method "Display" you're creating a new MyClass object, hence it has nothing to do with MyCla at all anymore.
Here is a code example of how to access the variable "i":
public class MyClass
{
protected int i;
public MyClass()
{
}
public virtual void Display()
{
Console.WriteLine("Base dis");
}
}
public class MyCla : MyClass
{
public MyCla()
{
}
int ij = 12;
public new void Display()
{
Console.WriteLine(this.i);
}
}
来源:https://stackoverflow.com/questions/25991006/cannot-access-variable-in-derived-class