7

In C#.Net, System.Diagnostics.Debug.WriteLine has several overloads, including these two:

//http://msdn.microsoft.com/en-us/library/cc190153.aspx
public static void WriteLine(string format, params Object[] args);

//http://msdn.microsoft.com/en-us/library/1w33ay0x.aspx
public static void WriteLine(string message, string category);

My intention is to call the first one with:

Debug.WriteLine("The path is {0}", myObj.myPath);

But it appears that I'm actually calling the second overload, because it is a more exact match.

Is there a simple way to indicate that I want the first one?

My best attempts so far are:

Debug.WriteLine("The path is {0}", new object[]{myObj.myPath});
Debug.WriteLine("The path is {0}", myObj.myPath, "");

But neither of these looks very elegant.

4

5 回答 5

6

尝试这个:

Debug.WriteLine("The path is {0}", (object)myObj.myPath);
于 2013-08-12T15:04:15.067 回答
4

这有点烦人。是的,有更好的方法。我使用Debug.Printdocs)具有相同效果但重载较少。这比试图观察您何时可能将两个字符串传递给WriteLine并强制转换为object和更少的输入要容易得多。例子:

Debug.Print("The path is {0}", myObj.myPath);
于 2013-08-12T15:18:55.633 回答
1

您可以避免使用重载,而只需传递格式化的字符串:

Debug.WriteLine(string.Format("The path is {0}", myObj.myPath));
于 2013-08-12T15:22:57.483 回答
1

对于像我这样的懒惰打字员,我只是使用

System.Diagnostics.Debug.Writeline("Hello {0}", "World", 1);

额外的参数强制正确的过载,并且是完全良性的。

于 2016-09-12T03:56:52.537 回答
0

我的意图是调用第一个:

第一个没有被调用,因为字符串显式重载优先。这就是 MSDN 不得不说的。

此方法语法中的 params 关键字意味着对象数组可以是单个值。String 对象是个例外。显式重载优先,因此单个字符串的 arg 值将默认为 Debug.WriteLine(String, String) 重载。

所以为了调用第一个,你必须将它转换为对象,这样显式重载就不会优先。

Debug.WriteLine("The path is {0}", (object)myObj.myPath);
于 2013-08-12T15:08:33.897 回答