如何将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?什么是这个额外的层购买你?

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...