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

时间:2021-09-09 16:12:17

Is it possible to call a method on the type you pass into your generic method?

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

Something like:

public class Blah<T>
{

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

    }

 }

3 个解决方案

#1


You can if there's some type to constrain T to:

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

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

public interface ISomeInterface
{
    int Age { get; }
}

The type could be a base class instead - but there has to be something to let the compiler know that there'll definitely be an Age property.

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

(In C# 4 you could use dynamic typing, but I wouldn't do that unless it were a particularly "special" situation which actually justified it.)

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

#2


Expanding on Jon's answer.

扩展乔恩的答案。

Yet another way is to take a functional approach to the problem

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

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

#3


How about:

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

#1


You can if there's some type to constrain T to:

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

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

public interface ISomeInterface
{
    int Age { get; }
}

The type could be a base class instead - but there has to be something to let the compiler know that there'll definitely be an Age property.

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

(In C# 4 you could use dynamic typing, but I wouldn't do that unless it were a particularly "special" situation which actually justified it.)

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

#2


Expanding on Jon's answer.

扩展乔恩的答案。

Yet another way is to take a functional approach to the problem

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

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

#3


How about:

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