gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 23:18:40 24 4
gpt4 key购买 nike

我有一个抽象类,我更多地将其用作接口(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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com