真是无法用返回类型超载? [英] Really impossible to use return type overloading?

查看:162
本文介绍了真是无法用返回类型超载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了一个小的DLL在MSIL有两种方法:

I made a small DLL in MSIL with two methods:

float AddNumbers(int, int)
int AddNumbers(int, int)

你们有些人可能知道,MSIL使您可以具有相同的参数,只要你有不同的返回类型的(所谓的返回类型超载)的方法。现在,当我试图从C#使用它,因为我还挺期待,它解雇了一个错误:

As some of you might know, MSIL allows you to make methods that have the same arguments as long as you have different kinds of return types (what is called return type overloading). Now, when I tried to use it from c#, as I was kinda expecting, it fired an error:

float f = ILasm1.MainClass.AddNumbers(1, 2);

该错误是:

调用不明确以下方法或属性之间:   ILasm1.MainClass.AddNumbers(INT,INT)'和'ILasm1.MainClass.AddNumbers(INT,INT)

The call is ambiguous between the following methods or properties: 'ILasm1.MainClass.AddNumbers(int, int)' and 'ILasm1.MainClass.AddNumbers(int, int)'

是C#真的不能返回类型不同加以区分?我知道我不能编程已作为唯一区别不同的返回类型的方法,但我总是有点以为它会知道如何处理它。

Is c# really incapable of distinguishing between different return types? I know I cannot program methods that have as only difference different return types, but I always kinda assumed it would know how to handle it.

推荐答案

像其他人一样说,没有C#不支持这一点。事实上,IL支持这一点,原因是因为你必须要明确有关的返回类型,就像参数。例如,在IL你会说

Like everyone else has said, no C# doesn't support this. In fact, the reason IL supports this, is because you have to be explicit about the return types, just like the parameters. For instance, in IL you'd say

ldarg.0
ldarg.1
call int AddNumbers(int, int)

IL并没有真正有方法重载的概念:浮动的addNumbers(INT,INT)没有任何关系 INT的addNumbers(INT, INT)无论如何,只要IL关注。你必须告诉IL编译器都在进步,而且也从未试图推断出你的意图(如如C#高级语言做的)。

IL doesn't really have a notion of method overloading: float AddNumbers(int, int) has no relation to int AddNumbers(int, int) whatsoever, as far as IL is concerned. You have to tell the IL compiler everything in advance, and it never tries to infer you intent (like higher level languages like C# do).

请注意,大多数.NET语言和C#有一个例外,返回类型重载:转换运营商。因此,

Note that most .NET languages and C# make one exception to return type overloading: conversion operators. So

public static explicit operator B(A a);
public static explicit operator C(A a);

被编译成

public static B op_Explicit(A a);
public static C op_Explicit(A a);

由于这是这样一个特定的极端必须加以支持原始类型(如int - >布尔)和引用类型转换(否则你会得到一个很迂腐的语言),这是处理,但不作为方法重载的情况。

Because this is such a specific corner case which has to be supported for primitive types (such as int -> bool) and reference type conversions (otherwise you'd get a very pedantic language), this is handled, but not as a case of method overloading.

这篇关于真是无法用返回类型超载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆