[英]C# default value
private static void print(StreamWriter sw, string mlog, bool screen)
{
DateTime ts = DateTime.Now;
sw.WriteLine(ts + " " + mlog);
if (screen == true)
{
Console.WriteLine(mlog);
}
}
我會使用print (sw,"write here", false)
進行調用。 90%的機會將使用false。 如何將默認值設置為false,這樣我打電話時就不必做額外的類型?
如果您使用的是C#4,則可以將screen
設為可選參數 :
// Note: changed method and parameter names to be nicer
private static void Print(StreamWriter writer, string log, bool screen = false)
{
// Note: logs should almost always use UTC rather than the system local
// time zone
DateTime now = DateTime.UtcNow;
// TODO: Determine what format you want to write your timestamps in.
sw.WriteLine(CultureInfo.InvariantCulture,
"{0:yyyy-MM-dd'T'HH:mm:ss.fff}: {1}", now, log);
if (screen)
{
Console.WriteLine(mlog);
}
}
只需使用= false
:
private static void print(StreamWriter sw, string mlog, bool screen = false)
這是有關C#中的命名和可選參數的更多信息。
請注意,這是C#4.0中的新增功能。 對於較舊的版本,請使用其他建議的方法重載。
private static void print(StreamWriter sw, string mlog)
{
print(sw, mlog, false);
}
對於較舊的版本,您只需提供2個替代:
private static void print(StreamWriter sw, string mlog)
{
print(sw,mlog, false);
}
如果您不使用C#4,請創建一個函數重載:
private static void Print(StreamWriter writer, string log)
{
Print(writer, log, false);
}
涉及可選參數的答案將起作用,但是某些語言不支持可選參數,因此它們無法從面向公眾的API調用此方法。
我會使用方法重載。
private static void print(StreamWriter sw, string mlog) {
print(sw, mlog, false);
}
private static void print(StreamWriter sw, string mlog, bool screen) { ... }
private static void print(StreamWriter sw, string mlog = "Write here", bool screen = false)
{
DateTime ts = DateTime.Now;
sw.WriteLine(ts + " " + mlog);
if (screen == true)
{
Console.WriteLine(mlog);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.