C# 可选参数或方法重载?

标签 c# coding-style overloading optional-parameters

<分区>

由于 C# 添加了可选参数,因此使用可选参数或方法重载被认为是一种更好的做法,或者在特定情况下您希望使用一个而不是另一个。也就是说,带有很多参数的函数更适合带有可选参数的函数?

最佳答案

可选参数很好,但应该在有意义的时候使用。可选参数通常会混淆方法的意图——如果有另一种选择,我会倾向于选择另一种方法。

部分需要可选参数和命名参数是因为 COM 允许可选参数和名称参数:

MSDN

Some APIs, most notably COM interfaces such as the Office automation APIs, are written specifically with named and optional parameters in mind. Up until now it has been very painful to call into these APIs from C#, with sometimes as many as thirty arguments having to be explicitly passed, most of which have reasonable default values and could be omitted.

来自 forums.asp.net 的 SomeNewKid 简明扼要地说:

http://forums.asp.net/t/386604.aspx/1

...overloaded methods are generally preferable to optional parameters. Why? To keep each of your methods clear in purpose. That is, each method should do one thing well. As soon as you introduce optional parameters, you are diluting the cleanliness of that method, and introducing branching logic that is probably best kept out of a method. This clarity of purpose becomes even more important when you start using inheritance. If you override a method that has one or more optional parameters, they become harder to work with. So, I'd suggest that for anything other than quick and dirty classes, you use overloading in preference to optional parameters.

请记住,可选参数是一种语法糖:

反射器 C#:

public class Class1
{
    // Methods
    public Class1()
    {
        this.Method1("3", "23");
    }

    public void Method1(string one, [Optional, DefaultParameterValue("23")] string two)
    {
    }
}

IL:

.class public auto ansi beforefieldinit Class1
    extends [mscorlib]System.Object
{
    .method public hidebysig specialname rtspecialname instance void .ctor() cil managed
    {
        .maxstack 8
        L_0000: ldarg.0 
        L_0001: call instance void [mscorlib]System.Object::.ctor()
        L_0006: nop 
        L_0007: nop 
        L_0008: ldarg.0 
        L_0009: ldstr "3"
        L_000e: ldstr "23"
        L_0013: call instance void WebApplication1.Class1::Method1(string, string)
        L_0018: nop 
        L_0019: nop 
        L_001a: ret 
    }

    .method public hidebysig instance void Method1(string one, [opt] string two) cil managed
    {
        .param [2] = string('23')
        .maxstack 8
        L_0000: nop 
        L_0001: ret 
    }

}

关于C# 可选参数或方法重载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6132010/

相关文章:

c# - 是否可以使对象公开类型参数的接口(interface)?

c# - 64 位类型库和 32 位类型库不同步

c# - 用 C# 编写的带有点击移动的 WPF 游戏

ruby - 我应该如何使用 Ruby?

c# - Mongodb C# 对嵌套数组使用 skip-limit

Cocoa NSTabView编码风格问题

c++ - std::for_each 优于 for 循环的优点

c++ - 在不分配新内存的情况下使用指针调用重载

C++ operator setter ruby​​ 风格

javascript - node.js - 重载函数