2012-10-11 42 views
4

我有一個函數,我想要使用泛型返回CreditSupplementTradeline或CreditTradeline。問題是如果我創建一個T ctl = new T(); ...我無法操作ctl,因爲VS2010不能識別它的任何屬性。這可以做到嗎?謝謝。如何實例化,操作並返回類型T

internal T GetCreditTradeLine<T>(XElement liability, string creditReportID) where T: new() 
    { 
     T ctl = new T(); 
     ctl.CreditorName = this.GetAttributeValue(liability.Element("_CREDITOR"), "_Name"); 
     ctl.CreditLiabilityID = this.GetAttributeValue(liability, "CreditLiabilityID"); 
     ctl.BorrowerID = this.GetAttributeValue(liability, "BorrowerID"); 
     return ctl; 
    } 

我得到這個錯誤:

Error 8 'T' does not contain a definition for 'CreditorName' and no extension method 'CreditorName' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?)

回答

14

你需要有相應的屬性的接口,例如像這樣:

internal interface ICreditTradeline 
{ 
    string CreditorName { get; set; } 
    string CreditLiabilityID { get; set; } 
    string BorrowerID { get; set; } 
} 

在你的方法,你需要添加限制爲T要求必須實現上述接口:

where T: ICreditTradeline, new() 

你的兩個類應實現的接口:

class CreditTradeline : ICreditTradeline 
{ 
    // etc... 
} 

class CreditSupplementTradeline : ICreditTradeline 
{ 
    // etc... 
} 

然後就可以調用與類的方法,你的類型參數:

CreditTradeline result = this.GetCreditTradeLine<CreditTradeline>(xElement, s); 
+0

完美,這正是我所期待的。謝謝。 – ElMatador

9

現在,你的程序只知道T是至少有一個object具有無參數構造函數。您需要更新where T以包含界面約束,該約束告訴您的函數T是包含CreditorName,CreditLiabilityIDBorrowerID的定義的某個接口的成員。你可以這樣做:

where T: InterfaceName, new() 
+0

謝謝你的回答。 :) – ElMatador