I am running into an issue with field inheritance. First I will explain how I would like it to work, and then ask for suggestions on how I can change the syntax to do what I want.
Here’s what I tried:
public abstract class A
{
public abstract D D1
{
get;
}
protected D _d2;
public virtual D D2
{
get { return _d2; }
set { _d2 = value; }
}
}
public abstract class B : A
{
protected D _d1;
public override D D1
{
get { return _d1; }
set
{
_d1 = value;
Update();
}
}
}
public abstract class C : A
{
public override D D1
{
get
{
return _d2.Find1();
}
}
public override D D2
{
get { return base.D2; }
set
{
base.D2 = value;
Update();
}
}
}
The problem is that A doesn’t compile because it can’t find an method to override with D1’s set. This how I expected it to work:
A ab = new B();
print(ab.D1);
ab.D1 = 4; // I would expect a compiler error
((B)ab).D1 = 4; // I would expect a compiler error
A ac = new C();
print(ac.D1);
ac.D1 = 4; // I would expect a compiler error
((C)ac).D1 = 4; // **I would expect this to work**
One solution I can see would be to add “set;” to A1’s D1 and throw a NotImplementedException if I try to use it in C, but that would prevent the issue from showing up in the compiler. Anyone know of a way around this issue? I would really like to keep them as fields so that I can display them using WPF.
Your error is with class
B. In classAyou defineD1aspublic abstract D D1 { get; }However inByou are attempting to overrideD1and add a setter — which is not defined by the abstract class. You’ll need to find another way to set the value inB. If other classes need to be able to setD1then you may want to defineD1aspublic abstract D D1 { get; set; }If
Bonly need to be able to set the value, just have it directly set the member value.