1

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

假设我有这样的课程设置:

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条件,但我不想做任何有条件的事情,因为这会使我的代码比它需要的大得多..

4

1 回答 1

1

像这样的东西?(还是我误解了?)

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 的限制...

于 2013-02-10T13:21:33.550 回答