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
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.
You can make A Generic
like so:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.