我正在尝试使用.Net 4.5 C#中的Generics做一些事情,老实说,我不确定它是否可能或它叫什么。这使搜索变得更加困难。
无论如何,最好用一个例子来解释。
假设我有一些界面:
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);
}
}
我一直在寻找和阅读任何我可以得到的东西。但似乎没什么好看的。也许我没有使用正确的术语进行搜索,因为老实说,我不知道它叫什么。
非常感谢任何帮助或指示。
答案 0 :(得分:0)
你没有给编译器足够的信息来推断它应该使用的类型参数。
类型推断是一个非常复杂的过程,但是,通常如果方法类型参数未出现在参数列表中,则不会执行任何类型推断对于类型参数。您可能想要阅读 C#规范。了解类型推断的细节。
希望有人可以进一步澄清它。