在C#中从另一个构造函数的主体调用一个构造函数 [英] Call one constructor from the body of another in C#

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

问题描述

我需要从另一个构造函数的主体中调用一个构造函数。我该怎么做?

I need to call one constructor from the body of another one. How can I do that?

基本上

class foo {
    public foo (int x, int y)
    {
    }

    public foo (string s)
    {
        // ... do something

        // Call another constructor
        this (x, y); // Doesn't work
        foo (x, y); // neither
    }
}


推荐答案

您不能。

您将必须找到一种链接构造函数的方法,如:

You'll have to find a way to chain the constructors, as in:

public foo (int x, int y) { }
public foo (string s) : this(XFromString(s), YFromString(s)) { ... }

或将您的构造代码移动到通用的设置方法中,如下所示:

or move your construction code into a common setup method, like this:

public foo (int x, int y) { Setup(x, y); }
public foo (string s)
{
   // do stuff
   int x = XFromString(s);
   int y = YFromString(s);
   Setup(x, y);
}

public void Setup(int x, int y) { ... }

这篇关于在C#中从另一个构造函数的主体调用一个构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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