我最近在学习C#,用到了一个String类的Format函数,然后F12进去看了一下它的定义,如下:
public static string Format(IFormatProvider? provider, string format, object? arg0)
public static string Format(IFormatProvider? provider, string format, object? arg0, object? arg1)
public static string Format(IFormatProvider? provider, string format, object? arg0, object? arg1, object? arg2)
public static string Format(IFormatProvider? provider, string format, params object?[] args)
public static string Format(string format, object? arg0)
请问为什么要写这么多的重载版本呢?只用
public static string Format(IFormatProvider? provider, string format, params object?[] args)
这一个不就够了吗?
场景不一样,用到的方法就不一样。
使用的时候,还要考虑性能的问题。如果只需要传一个参数,就没必要封装数组参数了。
工具类就需要考虑更多的方面,不止适用你个人,还要适用更多的使用者。
写多个重载函数的目的,是为了适应不同的场合,可能对你现在的情况,只有这一个就够用了。写重载的人,是应该用更多的想法的。
比如最后一个重载函数,就不需要provider,可能有默认的。这时候你就不需要非得定义一个provider,可以使得使用这个函数的人更为简单,方便。
应付参数个数,参数类型不同