具有不同返回类型的方法重载 [英] Method Overloading with different return type

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

问题描述

我想弄清楚这是模棱两可还是所提供的额外功能:

I am want to dig in that whether it is an ambiguity or an extra feature that is provided:

 public class Foo 
 { 
    public int Bar(){
       //code
    }

    public string Bar(int a){
       //code
    }
 }

任何有此经验的人,在带有不同参数的返回类型上重载应该是一个坏习惯,对吗?

Any one having any experience with this, overloading on return type with different parameters should be a bad practice, is it?

但是,如果重载是基于返回类型完成的,那么为什么这样做不起作用.

But if the overloading was done on the basis of return type then why this is not working for.

 public class Foo 
 { 
    public int Bar(int a){
       //code
    }

    public string Bar(int a){
       //code
    }
 }

因为如果我们调用obj.Bar();将无法决定要调用第一个还是第二个函数. ,它应该以错误结尾,任何人对此都有任何想法,为什么它允许第一个代码段运行.

As it will be unable to decide which function to call 1st or second, if we call obj.Bar(); , it should end in error do any one have any idea about it why it allows first code snippet to run.

推荐答案

C#规范(第10.6节)指出,重载成员的唯一返回类型和

The C# specification (section 10.6) states that overloaded members may not differ by only return type and as per http://msdn.microsoft.com/en-us/library/ms229029.aspx

根据您有关创建参数以仅支持不同返回类型的问题?我个人认为这是解决该问题的可怕方法.代码维护将变得困难,并且未使用的参数无疑是代码的味道.在这种情况下,是否真的需要重载该方法?还是属于该类?是否应该创建其他东西以从一种返回类型转换为另一种?您应该问所有的事情以得出更惯用的解决方案.

As per your question regarding creating parameters simply to support differing return types? I personally believe that is a terrible solution to the problem. Code maintenance will become difficult and unused parameters are a definite code smell. Does the method really need to be overloaded in that case? Or does it belong in that class? Should something else be created to convert from one return type to another? All things you should ask to derive a more idiomatic solution.

这篇关于具有不同返回类型的方法重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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