2013-09-30 25 views
0

我打電話有兩個不同的類,如下一個通用的方法:類屬性是不通用的方法可用的C#

FillDataPointsInOrder<Metrics>(dataPoints.Where(O => O.SortOrder != null).OrderBy(O => O.SortOrder)); 
FillDataPointsInOrder<Metric>(angieStatsCmp.GetDataColumns()); 


private void FillDataPointsInOrder<T>(IEnumerable<T> dataPoints) 
{ 
    foreach (T dpoint in dataPoints) 
    { 
     if (!dpoint.IsPhone) 
      FillDrp(this.EmailDrp, dpoint.Name, dpoint.MetricId.ToString(), dpoint.VName); 

     if (dpoint.IsPhone && this.IsPhoneShop) 
      FillDrp(this.PhoneDrp, dpoint.Name, dpoint.MetricId.ToString(), dpoint.VName); 
    } 
} 
在「FillDataPointsInOrder」

方法,我收到編譯錯誤:

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

Name,MetricId和VName屬性的相同錯誤。 不確定T爲什麼無法訪問Metrics和Metric的屬性。 如果我從泛型方法中刪除代碼,並直接在foreach中直接寫入數據點,那麼它工作正常。

有人可以提醒這裏有什麼問題嗎?

回答

1

FillDataPointsInOrder只知道它將被稱爲TT實際上可以是字符串,int或任何東西。

如果你想調用T上的屬性,你將不得不使用where約束。

但在這種情況下,它看起來像你的方法甚至不需要是通用的。 如果兩個MetricMetrics股基類或具有屬性的界面,你需要:

interface IMetric { 
    bool IsPhone {get; } 
} 

你可以只是有:

private void FillDataPointsInOrder(IEnumerable<IMetric> dataPoints) 

注意的IEnumerable是協變的,所以如果MetricIMetricIENumerable<Metric>IEnumerable<IMetric>

+0

好點。在問題中給出的例子中,如果相關的接口或基類存在,則首先不需要泛型方法。 – Xiaofu

1

如果你想這麼做,至少要告訴編譯器一些關於T的東西。你有一個接口是否有像你的類實現的IsPhone,Name,MetricId等成員?

如果是這樣,你可以在「這裏」約束添加到您的類定義:

public class Something<T> where T : ISomethingElse 

...其中ISomethingElse是實現IsPhone的接口。

相關問題