2011-10-07 69 views
0

我對C#比較陌生,所以請耐心等待。如何從通用方法獲得的對象調用函數?

我不知道如何更有效地執行此操作。

public static void Foo<T>(LinkedList<T> list) 
{ 
    foreach (Object o in list) 
    { 
     if (typeof(o) == typeof(MyClass1)) 
      (MyClass1)o.DoSomething(); 
     else if (typeof(o) == typeof(MyClass2)) 
      (MyClass2)o.DoSomething(); 

     ... 
     } 
    } 

我想做類似這樣的事情,或者比我現在做的更有效的事情。通過高效率,我的意思是這個程序運行得更快

public static void Foo<T>(LinkedList<T> list) 
{ 
    foreach (Object o in list) 
    { 
     o.DoSomething(); 
     } 
    } 

謝謝你的幫忙。

+0

做的項目需要以相同的順序被稱爲?你見過'OfType'嗎? –

+1

你可以使用接口嗎? –

+0

btw'typeof'是編譯時的東西。你需要檢查'null',然後使用'o.GetType()' –

回答

2

您正在尋找多態行爲。

abstract class Base // could also simply be interface, such as ICanDoSomething 
{ 
    public abstract void DoSomething(); 
} 

class MyClass1 : Base 
{ 
    public override void DoSomething() { /* implement */ } 
} 

在這種情況下,你可以定義你的方法來約束TBase,然後你被允許使用定義Base每個派生類中實現的方法。

public static void Foo<T>(LinkedList<T> list) where T : Base // or T : ICanDoSomething 
{  
    foreach (T item in list) 
    { 
     item.DoSomething(); 
    } 
} 

您通常不希望訴諸類型檢查內部方法,因爲您似乎已經實現了。這不是特別關於效率,因爲它是關於良好的編程習慣。每次添加新課程時,都必須回到方法並添加另一個校驗,這違反了所有種類的實體編程實踐。

2

實現一些接口,爲您的類型

public interface IMyType 
{ 
    void DoSomething(); 
} 

public class MyType1 : IMyType 
{ 
    public void DoSomething() { } 
} 

public class MyType2 : IMyType 
{ 
    public void DoSomething() { } 
} 

,並使用像

public static void Foo<T>(LinkedList<T> list) where T: IMyType 
{ 
    foreach (T o in list) 
    { 
     o.DoSomething(); 
     } 
    } 
1
public interface IDoSomething 
{ 
    void DoSomething(); 
} 

public static void Foo<T>(LinkedList<T> list) where T : IDoSomething 
{ 
    foreach (T o in list) 
    { 
     o.DoSomething(); 
    } 
} 
相關問題