[英]how do i refer to the derived type from the base class?
is there a keyword for the question "?"问题“?”有关键字吗? mark below or a way to achieve the same effect without using templates?在下面标记或不使用模板达到相同效果的方法?
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) {}
}
so that:以便:
var b1 = new B();
var b2 = new B();
var c = new C();
b1.Attach(b2);
b1.Attach(c); // should not compile
EDIT: with templates i mean type parameters such as Attach<T>(T x, T y)
// if we ignore that the example takes 1 argument编辑:对于模板,我的意思是类型参数,例如Attach<T>(T x, T y)
// 如果我们忽略该示例采用 1 个参数
Annoyingly, no.恼人的是,没有。 The closest you can get is:您可以获得的最接近的是:
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) { }
}
This doesn't however stop someone from writing:然而,这并不能阻止某人写作:
class D : A<B>
{
...
}
If you want to avoid this, you need a runtime check for this.GetType() == typeof(T)
or similar in A
's constructor.如果要避免这种情况,则需要在A
的构造函数中对this.GetType() == typeof(T)
或类似内容进行运行时检查。
You can make A Generic
like so:您可以像这样制作 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) {}
}
Than the following does not comile比以下不来
b1.Attach(c); // should not compile
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.