C# 从继承的类中获取类型

标签 c# inheritance

我有一个抽象类,我更多地将其用作接口(interface)。我的部分代码接受了抽象类,但我需要弄清楚继承它的是哪个类,以便我可以使用该类填充列表。

abstract class thingy
{
    //methods, variables, etc
}

class awsomeThing : thingy
{
    //Imagine there are more of these classes with different names...
}

我仅限于将抽象类(thingy)作为类型传递,但需要它的 awsomeThing 类型?我该怎么做呢?

编辑

太清楚了我在答案中寻找什么,使用 awsomeThing 的类有一个接近于此的方法:

void Start(thingy wantedType){

    List<thingy> collectionOfStuff = new List<thingy>( );

    for(int i = 0; i < 3; i++){
        //Here I want to add the type awsomeThing or one of the other classes
        //that derive from thingy but I don't know which one it is

        collectionOfStuff.Add(new ????); //what is wantedType in reality?
    }
}

最佳答案

可以通过GetType方法获取对象类型。

您还可以将虚拟方法添加到您的基类,返回一些枚举,这将允许您确定实际对象类型。

另一种选择是使用 is作为您需要确定对象类型的 if 语句中的条件。

关于C# 从继承的类中获取类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36271398/

相关文章:

c# - 如何从 P、Q 和 E 计算 RSA 加密的 D

c++ - 新类型(抽象类)

java - 我可以使用父对象调用子类方法吗?

c# - 如何使用 c# 从 xml 获取节点-我做错了什么?

c# - 如何在 C# 中定义 "anonymous namespace"?

c# - 影响迁移历史位置的 Entity Framework 自动迁移

java - 在Java中创建没有构造函数的子类实例

c# - 在 C# 控制台应用程序中打印 ASCII 艺术线条字符

继承方法的phpdoc

java - static Final的继承-->不可见