是否可以在传递给泛型方法的类型上调用方法?

Bla*_*man 5 c# generics

是否可以在传递给泛型方法的类型上调用方法?

就像是:

public class Blah<T>
{

    public int SomeMethod(T t)
    {
          int blah = t.Age;
          return blah;

    }

 }
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 19

如果有某种类型将T约束为:

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

public interface ISomeInterface
{
    int Age { get; }
}
Run Code Online (Sandbox Code Playgroud)

该类型可能是一个基类 - 但必须有一些东西让编译器知道肯定会有一个Age属性.

(在C#4中你可以使用动态类型,但我不会这样做,除非它是一个特别"特殊"的情况,实际上证明了它.)


Jar*_*Par 9

扩展乔恩的答案.

另一种方法是采用功能性方法解决问题

public int SomeMethod(T t, Func<T,int> getAge) {
  int blah = getAge(t);
  ...
}
Run Code Online (Sandbox Code Playgroud)