【问题标题】:C# how to pass a class as a parameter into a method and determining the base class of the parameter classC#如何将类作为参数传递给方法并确定参数类的基类
【发布时间】: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,并且这两个基类之上的不同类不一定相同,包括顶级类。

我无法更改任何代码,但我需要一种方法将最终派生自 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() 约束并且在没有重载的情况下仍然失败。

有没有其他方法可以做到这一点,还是根本不可能?

【问题讨论】:

    标签: c# class generics inheritance


    【解决方案1】:

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

    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());
        }
    }
    

    【讨论】:

    • 好的,但是有什么方法可以将它们组合成一个方法,因为我不知道我作为“T”传递的类是否具有基类 DomesticTestClass 或 InternationalTestClass?我可以像上面所说的那样重载它,还是应该只使用它们的基类并在其中放置一个 if 语句?
    猜你喜欢
    • 2011-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-05
    • 1970-01-01
    • 1970-01-01
    • 2015-12-26
    相关资源
    最近更新 更多