在C#中干掉对象实例化

mar*_*mka 1 .net c#

这段代码:

public class WidgetPlatform
{
    public Widget LeftmostWidget { get; set; }
    public Widget RightmostWidget { get; set; }

    public String GetWidgetNames()
    {
        return LeftmostWidget.Name + " " + RightmostWidget.Name;
    }
}
Run Code Online (Sandbox Code Playgroud)

不包含任何值得担心的重复,但它并不是特别强大.由于Widgets未经过空值检查,我们将留下一个漏洞的开头.我们可以进行空检查,但这感觉就像工作一样.这就是我真正想要的:

public class WidgetPlatform
{
    [Required]
    public Widget LeftmostWidget { get; set; }

    [Required]
    public Widget RightmostWidget { get; set; }

    public String GetWidgetNames()
    {
        return LeftmostWidget.Name + " " + RightmostWidget.Name;
    }
}
Run Code Online (Sandbox Code Playgroud)

理想情况下,如果在没有设置Widgets的情况下实例化对象,则会导致编译错误(最好的错误),但这看起来很高.有没有办法使这种语法至少在实例化时抛出错误?如果所有经过null检查的对象都从相同的类型继承,但没有多次继承会很快变得难看,那么有一种(相对)明显的方法可以使用反射.

Eoi*_*ell 5

构造函数有什么问题?

public class WidgetPlatform
{
    public Widget LeftmostWidget { get; set; }
    public Widget RightmostWidget { get; set; }

    public WidgetPlatform()
    {
        this.LeftMostWidget = new Widget();
        this.RightMostWidget = new Widget();
    }

    public WidgetPlatform(Widget left, Widget right)
    {
        if(left == null || right == null)
            throw new ArgumentNullException("Eeep!");

        this.LeftMostWidget = left;
        this.RightMostWidget = right;
    }


    public String GetWidgetNames()
    {
        return LeftmostWidget.Name + " " + RightmostWidget.Name;
    }
}
Run Code Online (Sandbox Code Playgroud)