[英]How do I use an overridden property value in a higher class?
我正在使用IoC在繼承的類中定義某些行為。 我有財產
protected virtual bool UsesThing { get { return true; } }
在我的頂級班上。
在我的繼承班上,我有
protected override bool UsesThing { get { return false; } }
我在頂層類中使用該屬性,並且在使用頂層值。 有沒有辦法使它使用繼承的值? 我認為這就是虛擬應該做的。
代碼示例:
using System;
public class Program
{
public static void Main()
{
B b = new B();
b.PrintThing();
//I want this to print the value for B
}
public class A
{
protected virtual bool Enabled
{
get
{
return true;
}
}
public void PrintThing()
{
Console.WriteLine(this.Enabled.ToString());
}
}
public class B : A
{
protected override bool Enabled
{
get
{
return false;
}
}
}
}
給定您的代碼示例,將按要求打印A
的Enabled
。
創建A
它對B
一無所知,因此從多態上講,您不能期望它使用其值。 這是因為,如果您有一個也從A
派生的類C
,它將不知道該使用什么!
另一方面,如果您寫過:
public static void Main()
{
A a = new B();
a.PrintThing();
}
在創建該類型的實例時,您會期望(正確)它將使用B
的替代。
您可以執行以下操作:
https://dotnetfiddle.net/SOiLni
A本身對B的實現一無所知,因此您必須實例化B的對象才能訪問其Boverride屬性。
小提琴的略微修改版本:
public class Program
{
public static void Main()
{
A a = new A();
a.PrintThing();
A newA = new B();
newA.PrintThing();
}
public class A
{
protected virtual bool Enabled
{
get
{
return true;
}
}
public void PrintThing()
{
Console.WriteLine(this.Enabled.ToString());
}
}
public class B : A
{
protected override bool Enabled
{
get
{
return false;
}
}
}
}
您的代碼必須存在其他問題。 此代碼將分別輸出“ true”和“ false”:
public class BaseClass {
public virtual bool DoesSomething {
get {
return true;
}
}
public void Print() {
Console.WriteLine(DoesSomething);
}
}
public class ChildClass : BaseClass {
public override bool DoesSomething {
get {
return false;
}
}
}
然后使用這些類:
BaseClass bc = new BaseClass();
bc.Print();
ChildClass sc = new ChildClass();
sc.Print();
如果我猜想您可能正在創建父類的實例,即使您的意圖是創建子類的實例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.