简体   繁体   English

我如何引用来自基础 class 的派生类型?

[英]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.

相关问题 C# 如何从基类中的派生类获取特定类型的所有字段? - C# How do I get all the fields of a specific type from a derived class within the base class? 如何从基类调用派生类方法? - How do I call a derived class method from the base class? 我如何将类(派生自通用“基”类)转换为该通用“基”类 - How do i convert a class (which is derived from a generic "base" class) to that generic "base" class 如何从基类获取派生类类型 - How the get derived class type from base class 如何在不事先知道类型的情况下使用XmlSerializer反序列化可能是基类或派生类的对象? - How do I use an XmlSerializer to deserialize an object that might be of a base or derived class without knowing the type beforehand? 从派生类将类型传递给基类 - Passing type to a base class from a derived class 在派生类中,如何从基类的属性类型中获取派生类型的属性? - In a derived class, how to have a property of a derived type from the type of the property in the base class? C#:如何从派生类的静态方法调用基类的静态方法? - C#: How do I call a static method of a base class from a static method of a derived class? 在基类型中引用派生类型是不好的形式? - Is it bad form to refer to a derived type in a base type? 调用方法时如何从基中获取派生类类型 - How to obtain the derived class type from base when calling a method
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM