C# 中的方法重载问题
在一次采访中他们问了这样的问题 有三种重载方法,
public int Addtoatal(int a, int b)
public int Addtoatal(int a, int b, int c)
public float Addtoatal(float a, float b)
有什么方法我可以写下一种方法,可以将 int 或 float 作为参数发送给该方法,我们真的可以在 OOPS 中做这样的事情吗?
任何帮助都会很棒
谢谢
In an interview they had asked an Question like this
there are three overloading methods
public int Addtoatal(int a, int b)
public int Addtoatal(int a, int b, int c)
public float Addtoatal(float a, float b)
is there any way i can write down one method where i can send an int or float as an parameter to the method ,can we really do any thing like this in OOPS
any help would be great
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,使用泛型:
如果方法需要使用任何运算符(+、-、*)等,则会出现问题,因为泛型类型无法确保类 T 具有运算符(运算符不能在接口中声明,因此你无法做出匹配的约束)。
在 .Net 4.0 中,您可以使用动态类型来获取动态变量来包含结果并添加到其中:
在其他 .Net 版本中,您需要像 MiscUtils 中的 Operator 类一样进行解决:c# 中添加 int、float 的通用方法
具有三个参数的第二个示例需要有不同的签名(在.Net 2.0中),因为它有更多的参数。
在 .Net 4.0 中,您可以仅对泛型类型使用可选参数,但不能对值类型执行此操作:
但是您可以对可空类型使用装箱,这适用于 int 和 double:
现在您可以做的下一个最好的事情是,如果您不想使用泛型,则将单个方法声明为 double (C# 4.0,因为可选参数):
在此示例中,int 值无论如何都会转换为 double,因此不会丢失数据,和int 可以隐式转换为 double,但返回值需要显式转换为 int。
Yes, using generics:
If the method needs to use any operators (+,-,*) etc. it will be problematic because generic types can't ensure that the class T has the operator (operators can't be declared in interfaces, and therefor you can't make a constraint to match).
In .Net 4.0 you could use dynamic typing to get a dynamic variable to contain the result and add to it:
In other .Net versions you'll need a work around like the Operator class in MiscUtils: generic method to add int, float, in c#
The second example with the three parameters would need to have a different signature (in .Net 2.0) because it has more parameters.
in .Net 4.0 you could just use optional parameters for generic types, but can't do it for value types:
But you could use boxing with nullable types, this would work with int and double:
Now the next best thing you could do, if you don't want to use generics, is have a single method declaration as double (C# 4.0, because of the optional parameter):
In this example the int values will be converted to a double anyway, so there's no loss of data, and the int can implicitly converted to double, but the return value would need to be explicitly cast to int.
是的,这称为泛型编程,请参阅 http://en.wikipedia.org/wiki/Generic_programming #Generic_programming_in_.NET
Yes, this is called generic programming see http://en.wikipedia.org/wiki/Generic_programming#Generic_programming_in_.NET
您可以使用泛型类型来完成此操作,并且对于不同参数的可能性,您可以使用
params
引用,并且您想要传递的参数数量并不重要。用法;
You can do it with generic types and for possibility of different paramaters you can use
params
reference and it doesn't matter parameters count that you want to pass.Usage;