如何让C#编译器推断泛型类型?

如何让C#编译器推断泛型类型?,第1张

概述我有以下方法: public TResult Get<TGenericType, TResult>() where TGenericType : SomeGenericType<TResult> where TResult : IConvertible { //...code that u 我有以下方法:
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 specificationint 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 cleanerint number = Get<SomeGenericType<int>>();

有办法做我想做的事吗?

解决方法 C#规范不允许推断一半的类型参数.您应该让编译器推断所有类型参数(这并不总是适用,如您的情况)或手动指定所有类型参数.

更新(回复评论):虽然我不是在C#团队中给出你的问题的绝对答案,但我的猜测是重载决策的复杂性(已经令人费解;你知道如果你阅读那个部分如果他们想要推断一半类型被推断而一半不被推断(特别是考虑到你可以仅通过泛型参数的数量来重载方法),那么C#规范)会显着增加.

总结

以上是内存溢出为你收集整理的如何让C#编译器推断泛型类型?全部内容,希望文章能够帮你解决如何让C#编译器推断泛型类型?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1248371.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-07
下一篇2022-06-07

发表评论

登录后才能评论

评论列表(0条)

    保存