2009-07-08 26 views

回答

19

你可以,如果有某種類型的約束噸至:

public int SomeMethod(T t) where T : ISomeInterface 
{ 
    // ... 
} 

public interface ISomeInterface 
{ 
    int Age { get; } 
} 

的類型可能是一個基類來代替 - 但必須有東西到讓編譯器知道肯定會有一個Age屬性。

(在C#4你可以使用動態類型,但我不會做,除非它是一個特別的「特殊」情況,實際上是合理的。)

+0

打我吧...再次刪除了我的恥辱後。 – 2009-07-08 13:50:34

+0

謝謝,現在我知道「T:IBlah在哪裏」的意思。 – Blankman 2009-07-08 14:27:26

9

擴大對喬恩的回答。

還有一種方法是採取功能性解決問題的方法

public int SomeMethod(T t, Func<T,int> getAge) { 
    int blah = getAge(t); 
    ... 
} 
+0

Grrrreatt心中都想到:) – leppie 2009-07-08 13:51:45

3

如何:

public class Blah 
{ 
    public int SomeMethod(Func<int> get_age) 
    { 
    int blah = get_age(); 
    return blah; 
    } 
} 
相關問題