2009-07-08 27 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; 
    } 
} 
相关问题