2013-02-10 86 views
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的條件,但我不想做任何事情有條件的,因爲這將使得比它需要的是我的代碼要大得多..

回答

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的約束......

+0

謝謝!不知道我錯過了:p – Ahmad 2013-02-10 16:08:53