加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何将C#泛型方法调用分派到专门的方法调用中

发布时间:2020-12-15 04:29:19 所属栏目:百科 来源:网络整理
导读:我有以下C#类: public class MyTypeT{ public void TryParse(string p_value) { T value ; Parser.TryParse(p_value,out value); // Do something with value }} 重点是调用正确的Parser.TryParse方法,具体取决于泛型类型T. 这使用以下静态类: static publ
我有以下C#类:
public class MyType<T>
{
   public void TryParse(string p_value)
   {
      T value ;

      Parser.TryParse(p_value,out value);

      // Do something with value
   }
}

重点是调用正确的Parser.TryParse方法,具体取决于泛型类型T.

这使用以下静态类:

static public class Parser
{
   static public void TryParse(string p_intput,out object p_output)
   {
      // Do something and return the right value
   }

   static public void TryParse(string p_intput,out double p_output)
   {
      // Do something and return the right value
   }

   static public void TryParse(string p_intput,out int p_output)
   {
      // Do something and return the right value
   }
}

我希望这可以工作:在最坏的情况下,将调用“对象”TryParse.相反,我有两个编译错误:

> CS1502:’Parser.TryParse(string,out object)’的最佳重载方法匹配有一些无效的参数
> CS1503:参数2:无法从’out T’转换为’out object’

问题1:我不明白为什么这不起作用:我可以天真,但不是所有C#对象都应该从“对象”派生出来?为什么T不能转换为对象?

问题2:如何将具有泛型类型T的方法分派到正确的非泛型方法中(即MyType< T> .TryParse根据正确的T类型调用正确的Parser.TryParse)?

注意

编辑问题以反映原始问题意图(如标题所示:如何将C#泛型方法调用分配到专门的方法调用中)

解决方法

实际上,ref和out参数不允许类型变化.因此,要将变量传递给期望out对象参数的方法,必须将该变量声明为object.

根据规范(§10.6.1.2和§10.6.1.3)

When a formal parameter is a reference parameter,the corresponding argument in a method invocation must consist of the keyword ref followed by a variable-reference (§5.3.3) of the same type as the formal parameter.

When a formal parameter is an output parameter,the corresponding argument in a method invocation must consist of the keyword out followed by a variable-reference (§5.3.3) of the same type as the formal parameter.

请参阅:Why do ref and out parameters not allow type variation?以了解原因.

Bonus question: How can I dispatch a method with generic type T into the right non-generic methods (i.e. MyType<T>.TryParse calling the right Parser.TryParse according to the right type of T)?

我要把它转回来.你为什么做这个?如果你正在调用MyType< T> .TryParse,比如MyType< int> .TryParse,为什么不直接调用Int32.TryParse?什么是这个额外的层购买你?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读