簡體   English   中英

我如何引用來自基礎 class 的派生類型?

[英]how do i refer to the derived type from the base class?

問題“?”有關鍵字嗎? 在下面標記或不使用模板達到相同效果的方法?

abstract class A
{
    public abstract void Attach(? x);
}

class B : A
{
    public override void Attach(B b) {}
}

class C : A
{
    public override void Attach(C c) {}
}

以便:

var b1 = new B();
var b2 = new B();

var c = new C();

b1.Attach(b2);
b1.Attach(c); // should not compile

編輯:對於模板,我的意思是類型參數,例如Attach<T>(T x, T y) // 如果我們忽略該示例采用 1 個參數

惱人的是,沒有。 您可以獲得的最接近的是:

abstract class A<T> where T : A<T>
{
    public abstract void Attach(T x);
}

class B : A<B>
{
    public override void Attach(B b) { }
}

class C : A<C>
{
    public override void Attach(C c) { }
}

然而,這並不能阻止某人寫作:

class D : A<B>
{
    ...
}

如果要避免這種情況,則需要在A的構造函數中對this.GetType() == typeof(T)或類似內容進行運行時檢查。

您可以像這樣制作 A Generic

abstract class A<T> where T : A<T>
{
    public abstract void Attach(T x);
}

class B : A<B>
{
    public override void Attach(B b) {}
}

class C : A<C>
{
    public override void Attach(C c) {}
}

比以下不來

b1.Attach(c); // should not compile

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM