有没有人尝试使用默认参数功能? [英] Have anyone try to use default parameter function?
本文介绍了有没有人尝试使用默认参数功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有两种方法
void 方法( string str = )
{
// logic
}
void 方法()
{
// 逻辑
}
我称之为
void main()
{
方法()
}
哪一个叫?
我尝试了什么:
面试问题被问到它会给出任何错误运行时间或编译时间?
解决方案
创建一个控制台应用程序并运行此代码以查看正在调用的方法。
使用系统;
class 计划
{
static void Main()
{
method();
Console.ReadLine();
}
静态 void 方法( string str = )
{
Console.WriteLine( method(string str = \\));
}
静态 void 方法()
{
Console.WriteLine( method());
}
}
如果您正在面试编程工作,并且您从未想过要自己尝试并看到它你真的以为你选择了合适的职业道路吗?
所以有人知道一种方法强制使用默认参数的方法吗?
我想到了一个针对这种情况的特殊代表的解决方案 - 但这不像我最初的想法那样工作:看看它的表现如何...
class 计划
{
委托 void methodDelegate( string str = ABC);
静态 void Main()
{
方法();
methodDelegate methodWithOptionalParameter = method;
methodWithOptionalParameter.Invoke();
Console.ReadKey();
}
静态 void 方法( string str = XYZ)
{
Console.WriteLine( 方法(字符串str = \{0} \),str);
}
静态 void 方法()
{
Console.WriteLine( method());
}
}
(提示:它使用委托定义中的默认值)
if i have two method
void method(string str="")
{
//logic
}
void method()
{
//logic
}
and i am calling it
void main()
{
method()
}
which one is called?
What I have tried:
interview question that is asked it gives any error runtime or compile time?
解决方案
Create a console application and run this code to see which method is being called.
using System; class Program { static void Main() { method(); Console.ReadLine(); } static void method(string str = "") { Console.WriteLine("method(string str = \"\")"); } static void method() { Console.WriteLine("method()"); } }
If you're interviewing for a programming job, and it never occurred to you to try it yourself and see, do you honestly think you've selected an appropriate career path?
So does anyone know a way to force the use of the method with the default parameter?
I thought of a solution with a special delegate for this case - But this doesn't work like I first thought: look how this behaves...
class Program { delegate void methodDelegate(string str = "ABC"); static void Main() { method(); methodDelegate methodWithOptionalParameter = method; methodWithOptionalParameter.Invoke(); Console.ReadKey(); } static void method(string str = "XYZ") { Console.WriteLine("method(string str = \"{0}\")", str); } static void method() { Console.WriteLine("method()"); } }
(hint: it uses the default value from the delegate Definition)
这篇关于有没有人尝试使用默认参数功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文