我有以下方法:
public TResult Get<TGenericType,TResult>() where TGenericType : SomeGenericType<TResult> where TResult : IConvertible { //...code that uses TGenericType... //...code that sets someValue... return (TResult) someValue; }
//Notice the duplicate int type specification int number = Get<SomeGenericType<int>,int>();
为什么我必须在方法定义中指定TResult?编译器已经知道了TResult,因为我在TGenericType中指定了它.理想情况下(如果C#编译器更聪明一点),我的方法看起来像这样:
public TResult Get<TGenericType>() where TGenericType : SomeGenericType<TResult> where TResult : IConvertible { //...code that uses TGenericType... //...code that sets someValue... return (TResult) someValue; }
所以用户可以像这样简单地使用它:
//Much cleaner int number = Get<SomeGenericType<int>>();
有办法做我想做的事吗?