具有类型比较的泛型构造函数



我想知道在C#中是否可以实现这样的功能。

假设我还有一个名为"Parent"的类和两个从"Parent"类继承的名为"Child1"和"Child2"的类。

///<summary>
/// Constructor for my form.
///</summary>
public FrmMainForm<T>(T thisChild)
{
    if(thisChild.GetType() == typeof(Child1)
    {
        // Do something
    }
    else if(thisChild.GetType() == typeof(Child2)
    {
        // Do something else
    }
}

使用构造函数调用它的代码可能如下所示:

FrmMainForm thisForm = FrmMainForm<Child1>(childObjectToPassIn);

我想使用泛型创建一个构造函数,并比较泛型的类型。这可能吗?

如果两个子类都继承自Parent,并且您无论如何都在使用类型检查,那么只需使类型为Parent:的参数

///<summary>
/// Constructor for my form.
///</summary>
public FrmMainForm(Parent thisChild)
{
    if(thisChild.GetType() == typeof(Child1)
    {
        // Do something
    }
    else if(thisChild.GetType() == typeof(Child2)
    {
        // Do something else
    }
}

或者只是添加重载(可能将任何"通用"coide重构为单独的方法:

///<summary>
/// Constructor for my form.
///</summary>
public FrmMainForm(Child1 thisChild)
{
    // Do something
}
public FrmMainForm(Child2 thisChild)
{
    // Do something else
}

你不能有一个构造函数来做这件事,但你可以有一个通用的工厂方法来做:

public FrmMainForm Create<T>(T thisChild) where T : Parent
{
    FrmMainForm result = new FrmMainForm();
    if(thisChild.GetType() == typeof(Child1)
    {
        // Do something
    }
    else if(thisChild.GetType() == typeof(Child2)
    {
        // Do something else
    }
    // return your form
}

如果您使构造函数private,这将成为构造表单的唯一方法

话虽如此,打开类型几乎总是设计糟糕的标志。我鼓励您重新思考为什么需要基于两个子类型的不同行为,以及是否可以将其重构为直接调用Parent类的单个方法。

您不应该在这里使用反射来检查对象的运行时类型。相反,您应该使用多态性来允许您相同地处理所有对象,并根据它们自己的定义分别使它们单独发挥作用。

父类型应该定义一组方法/属性,这些方法/属性表示您要对任何这些类型的对象执行的操作,然后每个子对象都可以根据需要实现方法/属性以使它们能够针对其特定差异适当地发挥作用。