0
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。如何使它默认为假,这样我在打电话时就不必做额外的类型?

4

7 回答 7

7

如果您使用的是 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);
    }
}
于 2012-07-02T19:00:32.827 回答
1

只需使用= false

private static void print(StreamWriter sw, string mlog, bool screen = false)

这是有关C# 中的命名和可选参数的更多信息。

请注意,这是 C# 4.0 中的新功能。对于旧版本,按照其他人的建议使用方法重载。

于 2012-07-02T19:00:30.720 回答
1
private static void print(StreamWriter sw, string mlog)
{
    print(sw, mlog, false);
}
于 2012-07-02T19:01:43.853 回答
1

对于旧版本,您可以简单地提供 2 个覆盖:

private static void print(StreamWriter sw, string mlog)
{ 
 print(sw,mlog, false);
}
于 2012-07-02T19:02:32.823 回答
1

如果您不使用 C# 4,请创建函数重载:

private static void Print(StreamWriter writer, string log) 
{ 
    Print(writer, log, false);
} 
于 2012-07-02T19:03:03.493 回答
1

涉及可选参数的答案将起作用,但某些语言不支持可选参数,因此它们无法从面向公众的 API 调用此方法。

我会使用方法重载..

private static void print(StreamWriter sw, string mlog) {
    print(sw, mlog, false);
}

private static void print(StreamWriter sw, string mlog, bool screen) { ... }

于 2012-07-02T19:04:46.537 回答
1
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);
        }
    }
于 2012-07-02T20:07:25.757 回答