我刚刚遇到了C#5来电者信息属性(http://msdn.microsoft.com/en-us/library/hh534540.aspx)。
这似乎是一个非常有用的功能,我已经阅读了一些文档(http://www.codeproject.com/Tips/606379/Caller-Info-Attributes-in-Csharp)。
但是,我只是想知道:为什么必须传递默认值?它们是如何使用的?
以下示例代码显示了如何使用调用者信息属性:
public static void ShowCallerInfo([CallerMemberName]
string callerName = null, [CallerFilePath] string
callerFilePath = null, [CallerLineNumber] int callerLine=-1)
{
Console.WriteLine("Caller Name: {0}", callerName);
Console.WriteLine("Caller FilePath: {0}", callerFilePath);
Console.WriteLine("Caller Line number: {0}", callerLine);
}
我的问题是:什么是默认值 null
, null
,和 -1
用于?上面的代码与以下内容有何不同:
public static void ShowCallerInfo([CallerMemberName]
string callerName = "hello", [CallerFilePath] string
callerFilePath = "world", [CallerLineNumber] int callerLine=-42)
{
Console.WriteLine("Caller Name: {0}", callerName);
Console.WriteLine("Caller FilePath: {0}", callerFilePath);
Console.WriteLine("Caller Line number: {0}", callerLine);
}
我理解它的方式,这些是可选参数,编译器提供默认值,替换我们分配的任何默认值。在那种情况下,我们为什么要指定默认值?是否有一些奇怪的边缘情况,编译器可能无法填写值,并转向我们提供的默认值?如果没有,那么为什么要求我们输入这些数据呢?要求开发者提供永远不会使用的默认值似乎相当笨拙。
免责声明:我试过谷歌搜索,但我找不到任何东西。我几乎害怕在SO上提问,因为大多数这样的新手问题都遭遇了这种敌意,但作为最后的手段,我会冒一个问题。主持人/高级用户,没有违法行为 - 在发布此内容之前,我确实尝试过在其他地方查找信息。