正在创建具有类继承的模板类型的实例

本文关键字:类型 实例 继承 创建 | 更新日期: 2023-09-27 17:58:28

我有一个问题似乎无法解决。

假设我有这样的类:

public abstract class GenericCustomerInformation
{
    //abstract methods declared here
}
public class Emails : GenericCustomerInformation
{
    //some new stuff, and also overriding methods from GenericCustomerInformation
}
public class PhoneNumber : GenericCustomerInformation
{
    //some new stuff, and also overriding methods from GenericCustomerInformation
}

现在假设我有一个这样的功能设置:

private void CallCustomerSubInformationDialog<T>(int iMode, T iCustomerInformationObject)
{
    //where T is either Emails or PhoneNumber
    GenericCustomerInformation genericInfoItem;
    //This is what I want to do:
    genericInfoItem = new Type(T);
    //Or, another way to look at it:
    genericInfoItem = Activator.CreateInstance<T>(); //Again, does not compile
}

CallCustomerSubInformationDialog<T>函数中,我有一个基本类型为GenericCustomerInformation的变量,我想用T(派生类型之一:EmailsPhoneNumber)中的任何变量实例化它

一个简单的方法是使用一堆if条件,但我不想做任何有条件的事情,因为这会使我的代码比需要的要大得多。。

正在创建具有类继承的模板类型的实例

可能是这样的吗?(或者我误解了?)

private void CallCustomerSubInformationDialog<T>(int iMode, T iCustomerInformationObject) where T: GenericCustomerInformation, new()
{
    //where T is either Emails or PhoneNumber
    GenericCustomerInformation genericInfoItem;
    //This is what you could try to do:
    genericInfoItem = new T();
}

注意:注意T…的限制