我刚刚发现了C# 5的Caller Info Attributes(http://msdn.microsoft.com/en-us/library/hh534540.aspx),这似乎是一个非常有用的功能。我已经阅读了一些文档 (http://www.codeproject.com/Tips/606379/Caller-Info-Attributes-in-Csharp)。不过,我想知道:为什么要传入默认值?它们如何使用?下面的示例代码展示了如何使用Caller Info Attributes:
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);
}
我理解这些是可选参数,编译器会提供默认值来替换我们赋的默认值。既然如此,为什么还要指定默认值?是否存在一些奇怪的边缘情况,编译器无法填充值并回退到我们提供的默认值?如果不是,那我们为什么要输入这些数据呢?让开发人员提供永远不会使用的默认值似乎相当笨拙。免责声明:我试图在Google上搜索相关信息但没有找到任何答案。我几乎不敢在SO上问问题,因为大多数像我这样的新手问题都会受到强烈反感,但作为最后的办法,我打算冒险问一个问题。版主/高级用户,无意冒犯-在发布此帖之前,我确实尝试在其他地方寻找信息。