是否可以使具有两个类型参数的泛型方法仅推断其中一个?
Is is possible to make a generic method with two type arguments only infer one of them?
我有一个类似 public static TOut Method<TIn, TOut>(TIn in)
的方法,带有约束 where TIn: class, Interface<TOut>
。
我在使用它的时候是不是总是需要写Method<ClassIn, ClassOut>(ObjectIn);
,或者有什么方法可以让TIn
由参数推断出来所以我只需要写Method<ClassOut>(ObjectIn);
? ClassOut
会不时变化,所以我不能每次都为它写一个静态的 class。
此外,C# 不能从约束中推断出类型,所以不可能同时推断出 TIn
和 TOut
吗?
是的,您始终需要指定这两种类型。类型推断仅在指定所有类型参数时有效。
是的,C# 编译器无法根据约束推断类型。它只能根据您作为参数传入的类型推断类型。
旁注,there is an open issue关于在这方面改进类型推断,但它似乎没有很高的优先级。
我有一个类似 public static TOut Method<TIn, TOut>(TIn in)
的方法,带有约束 where TIn: class, Interface<TOut>
。
我在使用它的时候是不是总是需要写Method<ClassIn, ClassOut>(ObjectIn);
,或者有什么方法可以让TIn
由参数推断出来所以我只需要写Method<ClassOut>(ObjectIn);
? ClassOut
会不时变化,所以我不能每次都为它写一个静态的 class。
此外,C# 不能从约束中推断出类型,所以不可能同时推断出 TIn
和 TOut
吗?
是的,您始终需要指定这两种类型。类型推断仅在指定所有类型参数时有效。
是的,C# 编译器无法根据约束推断类型。它只能根据您作为参数传入的类型推断类型。
旁注,there is an open issue关于在这方面改进类型推断,但它似乎没有很高的优先级。