繁体   English   中英

C#如何将类作为参数传递给方法并确定参数类的基类

[英]C# how to pass a class as a parameter into a method and determining the base class of the parameter class

所以我一直在通过在列表的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

DomesticTestClasInternationalTestClass都源自相同的基类: TestClass ,而这两个基类之上的不同类不一定相同,包括顶级类。

我无法更改任何代码,但是我需要一种方法,该方法将最终从DomesticTestClassInternationalTestClass派生的特定类传递给方法,然后决定是否将特定类添加到列表中,具体取决于它具有的基类。

我试过只是一个普通的方法:

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()约束,并且在没有重载的情况下仍然失败。

还有另一种方法可以做到吗?

由于您正在创建一个新类以将其添加到集合中,因此需要将一个new约束添加到通用类型参数中,以告诉编译器有一个保证的公共无参数构造函数。

public void AddADomesticTestClass<T>() where T: DomesticTestClass, new()
{
    SupportedTests.Add(new T());
}

public void AddAnInternationalTestClass<T>() where T: InternationalTestClass, new()
{
    SupportedTests.Add(new T());
}

或者

public void AddATestClass<T>() where T: TestClass, new()
{
    if (typeof(T).IsAssignableFrom(typeof(DomesticTestClass))
        || typeof(T).IsAssignableFrom(typeof(InternationalTestClass)))
    {
        SupportedTests.Add(new T());
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM