[英]Generic Generics or Type argument inference and inheritance
我正在尝试使用.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与Class 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#规范 。 了解类型推断的详细信息。
希望有人可以进一步澄清。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.