其他分享
首页 > 其他分享> > CodeGo.net>使用命名和可选参数来区分构造函数

CodeGo.net>使用命名和可选参数来区分构造函数

作者:互联网

设想一个类,原则上可以通过指定两个属性之一的值来创建,这两个属性恰好具有相同的类型.以下代码通过结合使用named and optional parameters来区分这两个构造函数来实现此目的:

class Program
{
    static void Main()
    {           
        //Note: these 2 ctors are distinguished only by the argument naming convention:
        thing thingWithMass = new thing(mass: 10);
        thing thingWithVolume = new thing(vol: 25);
    }

    class thing
    {
        int Density = 3;
        int Mass;
        int Vol;
        public thing(int mass)
        {
            Mass = mass;
            Vol = Mass/Density;
        }

        // Note the use of the optional variable to distinguish this ctor:
        public thing(int vol, bool isVol=true)
        {
            Vol = vol;
            Mass = Vol * Density;
        }
    }
}

因此(有些令人惊讶)此代码可以编译并完美地工作,但是它是不好的形式吗?似乎有点欺骗,我想知道是否存在我不容易发现的潜伏危险?有闻吗

注意:在这种特殊情况下,我意识到我可以用一个看起来像这样的构造函数完成基本上相同的事情:

public thing(int mass=0, int vol=0) //plus a couple of if() statements in the body

但是在我的实际情况中,还涉及许多其他参数,并将它们全部组合到一个构造函数中会有点笨拙且难以阅读.

解决方法:

如果您的类有许多构造函数,它们的逻辑和语法类型大不相同,请考虑使用静态工厂方法:

public static Thing CreateFromMass(int mass)
{
    return new Thing(mass, 0);
}

public static Thing CreateFromVol(int vol)
{
    return new Thing(0, vol);
}

如果使用这样的工厂方法,则可以使构造函数不公开.

不建议根据参数名称区分构造函数,因为这在C#中非常少见.请注意,您还必须使用带有可选参数的技巧来实现这一目标—明确表明您做错了事.

标签:named-parameters,constructor,optional-parameters,c
来源: https://codeday.me/bug/20191029/1957510.html