微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我有以下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?什么是这个额外的层购买你?

原文地址:https://www.jb51.cc/csharp/91348.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐