我有一个我似乎无法解决的问题。
假设我的课程设置如下:
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
中的任何一个来实例化它(其中一个派生类型:{ {1}}或Emails
)
一个简单的事情是使用一堆PhoneNumber
条件,但我不想做任何有条件的事情,因为这将使我的代码比它需要的大得多..
答案 0 :(得分: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 ...的限制