我正在尝试在.Net 4.5 C#中使用泛型做一些事情,老实说,我不确定这是否可能,也不确定它被称为什么。这使得搜索变得更加困难。
无论如何,最好用一个例子来解释。
假设我有一些接口:
public interface ISomeBase {}
及其实现的示例
public class AnObject : ISomeBase {}
public class AnOtherObject : ISomeBase {}
然后我得到了ClassA,它有一些通用方法,比如
public class ClassA
{
public T SomeMethod1<T>() where T : class, ISomeBase
{
//Do some stuff and return some T
return default(T);
}
public List<T> SomeMethod2<T>(Expression<Func<T,object>> someExpression ) where T : class, ISomeBase
{
//Do some stuff and return some List<T>
return new List<T>();
}
}
我想能够像这样使用它(我可以很容易地使用):
public class SomeImplementation
{
public void Test()
{
var obj = new ClassA();
var v = obj.SomeMethod1<AnObject>();
var v2 = obj.SomeMethod2<AnOtherObject>((t) => t.ToString());
}
}
但我也希望能够像这样使用它(由于需要类型参数,这将无法正常工作。我知道ClassB中的t与A类中的每个方法中的t都不同:
public class ClassB<T> : ClassA where T: ISomeBase
{
public T Tester()
{
//This is not possible and requires me to add a Type argument.
return SomeMethod1(); //I would like to leave out the type argument and have the compiler infer what it is
// Some of the time I want to be able to apply the same type to all methods on ClassA.
// And some of the time I want to be able to specify the type arguments on a per method basis
}
}
我想避免把ClassA包装成这样的东西:
public class ClassA<T> : ClassA where T : class, ISomeBase
{
public T SomeMethod1()
{
return SomeMethod1<T>();
}
public List<T> SomeMethod2(Expression<Func<T, object>> someExpression)
{
return SomeMethod2<T>(someExpression);
}
}
我一直在寻找和阅读任何我能找到的东西。但似乎没有什么合适的。也许我没有使用正确的术语进行搜索,因为老实说,我不知道它叫什么。
任何帮助或建议都将不胜感激。
您没有为编译器提供足够的信息来推断出它应该使用的类型参数。
类型推理是一个非常复杂的过程,但是,通常,如果方法类型参数没有出现在参数列表中,则不会对该类型参数执行类型推理。您可能想阅读C#规范。了解类型推理的细节。
希望有人能进一步澄清。