简体   繁体   English

C#默认值

[英]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);
        }
    }

I would use print (sw,"write here", false) to call. 我会使用print (sw,"write here", false)进行调用。 90% chance I will use false. 90%的机会将使用false。 how to make it the default to be false that way I dont have to do the extra type when I do the call? 如何将默认值设置为false,这样我打电话时就不必做额外的类型?

If you're using C# 4, you can make screen an optional parameter : 如果您使用的是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);
    }
}

Just use = false : 只需使用= false

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

Here's a little more info on Named and Optional Arguments in C# . 这是有关C#中的命名和可选参数的更多信息。

Note that this is new in C# 4.0. 请注意,这是C#4.0中的新增功能。 For older versions, use method overloads as others have suggested. 对于较旧的版本,请使用其他建议的方法重载。

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

For older versions you can simply provide 2 overrides: 对于较旧的版本,您只需提供2个替代:

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

If you aren't using C# 4, create a function overload: 如果您不使用C#4,请创建一个函数重载:

private static void Print(StreamWriter writer, string log) 
{ 
    Print(writer, log, false);
} 

The answers involving optional parameters will work, but some languages do not support optional parameters, so they could not call this method from a public-facing API. 涉及可选参数的答案将起作用,但是某些语言不支持可选参数,因此它们无法从面向公众的API调用此方法。

I would go with method overloading.. 我会使用方法重载。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM