[英]Is it possible for a derived class to hold a reference to an existing base class in C#?
假設下面的代碼。 是否可以使用現有基類的實例創建派生類? 還是在這里使用擴展方法是最好的解決方案?
public class TestThis
{
public void Test1()
{
A a = GetAFromExternalSystem();
B b = new B(a);
a.Value = 5;
b.Value == 5; //want this line to return true. In other words, b to hold a reference to a.
}
private A GetAFromExternalSystem()
{
return new A();
}
}
public class A
{
public string Name { get; set; }
public int Value { get; set; }
}
public class B : A
{
public B(A a)
{
this = a; //Cannot assign to 'this' because it is read-only
}
public int Ranking { get; set; }
}
通常是這樣進行的:
public class A
{
public A(string name, int value)
{
this.Name = name;
this.Value = value;
}
public string Name { get; set; }
public int Value { get; set; }
}
public class B : A
{
public B(A a) : this(a.Name, a.Value, 0)
{
}
public B(string name, int value, int ranking) : base(name, value)
{
this.Ranking = ranking;
}
public int Ranking { get; set; }
}
請仔細研究並確保您了解其工作原理。 如果您對它的工作方式有疑問,請發布一個新的,准確的,明確的問題。
現在,它沒有您想要的屬性,即對A的更新也會對B的更新。要做這種奇怪的事情的方法是放棄B與A之間的一種關系:
public class B
{
private A a;
public B(A a)
{
this.a = a;
}
public int Ranking { get; set; }
public int Value
{
get { return this.a.Value; }
set { this.a.Value = value; }
}
public string Name
{
get { return this.a.Name; }
set { this.a.Name = value; }
}
}
現在,如果您想讓B都推遲到A,並且B又是A的實例,那么您將遇到一個更困難的問題; A的屬性必須是虛擬的,並在B中覆蓋。我將其保留為練習。
但實際上聽起來您在嘗試做一些非常奇怪的事情。 您能否描述您實際要解決的問題? 您做錯了,這很不錯。
不,您不能這樣做。
創建派生類時, 還將創建基類,並且該基類是派生類的“一部分”。 您不能簡單地將派生類的基礎部分重新分配給其他內容。
修復非常簡單,只需復制您關心的成員即可。
盡管這可能是X / Y問題 ,但是您不能使用派生類來執行此操作。 要實現您在測試用例中想要實現的目標,可以使用包裝器類來完成
public class TestThis
{
public void Test1()
{
A a = GetAFromExternalSystem();
B b = new B(a);
a.Value = 5;
b.Value == 5;
}
private A GetAFromExternalSystem()
{
return new A();
}
}
public class A
{
public string Name { get; set; }
public int Value { get; set; }
}
public class B // B acts as a 'wrapper' for A
{
public B(A a)
{
this.A = a;
}
public A A { get; set; }
public int Value {
get { return A.Value; }
}
public int Ranking { get; set; }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.