是否可以调用您传入您的泛型方法的类型的方法?是否可以调用您传入您的泛型方法的类型的方法?
喜欢的东西:
public class Blah<T>
{
public int SomeMethod(T t)
{
int blah = t.Age;
return blah;
}
}
是否可以调用您传入您的泛型方法的类型的方法?是否可以调用您传入您的泛型方法的类型的方法?
喜欢的东西:
public class Blah<T>
{
public int SomeMethod(T t)
{
int blah = t.Age;
return blah;
}
}
你可以,如果有某种类型的约束吨至:
public int SomeMethod(T t) where T : ISomeInterface
{
// ...
}
public interface ISomeInterface
{
int Age { get; }
}
的类型可能是一个基类来代替 - 但必须有东西到让编译器知道肯定会有一个Age
属性。
(在C#4你可以使用动态类型,但我不会做,除非它是一个特别的“特殊”情况,实际上是合理的。)
扩大对乔恩的回答。
还有一种方法是采取功能性解决问题的方法
public int SomeMethod(T t, Func<T,int> getAge) {
int blah = getAge(t);
...
}
Grrrreatt心中都想到:) – leppie 2009-07-08 13:51:45
如何:
public class Blah
{
public int SomeMethod(Func<int> get_age)
{
int blah = get_age();
return blah;
}
}
打我吧...再次删除了我的耻辱后。 – 2009-07-08 13:50:34
谢谢,现在我知道“T:IBlah在哪里”的意思。 – Blankman 2009-07-08 14:27:26