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

查看:29
本文介绍了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...

推荐答案

您可以将公共逻辑分解为私有方法,例如从两个构造函数调用的名为 Initialize 的方法.

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天全站免登陆