C#构造函数重载 [英] C# constructors overloading

查看:124
本文介绍了C#构造函数重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何使用构造函数在C#这样的:

How I can use constructors in C# like this:

public Point2D(double x, double y)
{
    // ... Contracts ...

    X = x;
    Y = y;
}

public Point2D(Point2D point)
{
    if (point == null)
        ArgumentNullException("point");
    Contract.EndContractsBlock();

    this(point.X, point.Y);
}



我需要它不是从另一个构造复制代码...

I need it to not copy code from another constructor...

推荐答案

你可以将你常用的逻辑来一个私有方法,例如名为初始化这会从两个构造调用。

You can factor out your common logic to a private method, for example called Initialize that gets called from both constructors.

由于要执行你不能再打构造链接参数验证的事实。

Due to the fact that you want to perform argument validation you cannot resort to constructor chaining.

例如:

public Point2D(double x, double y)
{
    // Contracts

    Initialize(x, y);
}

public Point2D(Point2D point)
{
    if (point == null)
        throw new ArgumentNullException("point");

    // Contracts

    Initialize(point.X, point.Y);
}

private void Initialize(double x, double y)
{
    X = x;
    Y = y;
}

这篇关于C#构造函数重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆