【发布时间】:2017-09-19 18:34:38
【问题描述】:
所以我一直在通过调用列表的 add 方法中的构造函数将一个类添加到类列表中:
SupportedTests.Add(new SpecificTestClass27());
但是,我使用的类是派生类(大多数时候它们有 4 或 5 个基类链),我只想根据它们使用的基类将它们添加到列表中(不是直接基类,但它是几个基类)
链式基类示例:
public class SpecificTestClass27 : SpecificTestClass27_base
public abstract class SpecificTestClass27_base: OperationTestClass_base
public abstract class OperationTestClass_base: DomesticTestClass
或
public abstract class OperationTestClass_base: InternationalTestClass
DomesticTestClass 和 InternationalTestClass 都派生自同一个基类:TestClass,并且这两个基类之上的不同类不一定相同,包括顶级类。
我无法更改任何代码,但我需要一种方法将最终派生自 DomesticTestClass 或 InternationalTestClass 的特定类传递到方法中,然后决定是否将特定类添加到列表中取决于它具有哪个基类。
我试过只做一个普通的方法:
public void AddaTestClass(object SpecificTestClass)
{
if (base == DomesticTestClass) { SupportedTests.Add(new SpecificTestClass()); }
}
但它不喜欢参数是一个类。 当我尝试使用具有重载的泛型时:
public void AddaTestClass<<"SpecificTestClass">>() where SpecificTestClass : DomesticTestClass
{
SupportedTests.Add(new SpecificTestClass());
}
与
public void AddaTestClass<<"SpecificTestClass">>() where SpecificTestClass : InternationalTestClass
{
}
注意:我的程序中没有引号中的SpecificTestClass,它只是不会出现在没有引号的克拉之间
这不允许我调用类的构造函数,因为它没有 new() 约束并且在没有重载的情况下仍然失败。
有没有其他方法可以做到这一点,还是根本不可能?
【问题讨论】:
标签: c# class generics inheritance