2015-11-05 49 views
2

我想編寫一個通用方法,輸入具有通用對象列表。我想在每個列表項上調用一個方法。通用類型參數的調用方法

我試圖做的是寫一樣的東西:

public void ResetPointProperties<T> (List<T> Points) 
{ 
    foreach (T point in Points) 
    { 
     point.Reset(); 
    } 
} 

我怎麼能說我的列表項Reset()

回答

5

你快到了。然而,缺少的是,現在編譯器不知道/每個T是否有reset()方法。因此,您必須將constraint添加到T參數中,該參數需要T才能實現接口或從聲明此類reset()方法的類繼承。

例如,讓我們假設你的地方有以下接口:

public interface IThing 
{ 
    void reset(); 
} 

然後,您可以按如下聲明你以上的方法:

public void ResetPointProperties<T> (List<T> Points) 
    where T : IThing 

該強制執行任何類型傳遞給T類型參數必須實施IThing。作爲回報,編譯器可以保證您的方法中的point實際上有一個reset()方法,您可以調用。

4

如果你的問題是「我怎樣才能調用Reset()T,然後 - 正確地做到這一點 - 你需要引入generic type constraint

你可以這樣做,使用接口:

public interface IResettable 
{ 
    void Reset(); 
} 

並應用:

public void ResetPointProperties<T> (List<T> Points) 
    where T : IResettable 

現在,當你調用ResetPointProperties()方法,必須用List<T>,其中T實現了論點這樣做界面IResettable。例如,一個Point類:

public class Point : IResettable 
{ 
    public void Reset() 
    { 
     X = 0; 
     Y = 0; 
    } 
} 
+0

雖然IST必須是:'公共無效ResetPointProperties (名單點)其中T:IResettable {'...將大括號放在條件之後。 – Camo

+0

@Rinecamo是啊,謝謝,我複製粘貼OP的Java風格的大括號而不留意。 – CodeCaster

1

好吧,讓我們來看看都得到它可能的方式工作:

A.一般制約

public void ResetPointProperties<T> (List<T> Points) 
    where T : ISomeInterface // interface must contain .Reset method 
{ 
    foreach (T point in Points) 
     point.Reset();  
} 

類型B.調用方法前檢查並顯式轉換:

public void ResetPointProperties<T> (List<T> Points) 
{ 
    if(typeof(T) != typeof(Point)) return; 

    foreach (T point in Points) 
    { 
     Point p = point as Point; 
     p.Reset();  
    } 
} 

C.通過反射:

public void ResetPointProperties<T> (List<T> Points) 
{ 
    if(typeof(T) != typeof(Point)) return; 
    MethodInfo method = typeof(T).GetMethod("Reset"); 

    foreach (T point in Points) 
    { 
     t.Invoke(point, null); 
    } 
} 

D.使用dynamic

public void ResetPointProperties<T> (List<T> Points) 
{ 
    foreach (dynamic point in Points) 
    { 
     point.Reset(); 
    } 
} 

如果有可能最好的解決辦法是使用接口和泛型約束。接下來會進行轉型,然後做一些事情(例如,在類來自某個外部dll且您無法控制它的情況下)。一般不建議反思和動態,因爲它們很慢,幾乎不可能進行單元測試。

但是有時使用反射和動力學可能會在一些複雜的情況下解決相當長的時間。

假設您在數據庫40倍的模型和視圖模型3爲每本40款,並要他們在某些方法來繪製...

相關問題