简体   繁体   中英

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. 90% chance I will use 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?

If you're using C# 4, you can make screen an optional parameter :

// 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 :

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

Here's a little more info on Named and Optional Arguments in C# .

Note that this is new in 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:

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

If you aren't using C# 4, create a function overload:

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.

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);
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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