C# - 构造函数的链调用 [英] C# - Chain Calling of Constructor

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

问题描述

我目前正在学习C#,我正在学习构造函数和构造函数的链调用,以便不必在每个构造函数中粘贴相同的代码(变量的值相同)。

I'm currently studying C# and I'm learning about constructors and the chain calling of constructors so as not to have to paste the same code (the same value for variables) in each constructor.

我有三个构造函数,一个没有参数,一个有三个参数,一个有四个参数。我要做的是,使用默认构造函数调用具有三个参数的构造函数,传递参数(变量)的默认值和具有三个参数的构造函数,我正在寻找的是调用构造函数与四参数。我似乎有第一个排序列出默认值,但我努力如何写三个参数的构造函数,然后得到这个调用构造函数与四个参数,如果需要。

I have three constructors, one with no parameters, one with three parameters and one with four parameters. What I'm looking to do is, use the default constructor to call the constructor with three parameters, passing default values for the parameters (variables) and the constructor that has three parameters, I'm looking for that to call the constructor with four parameters. I seem to have the first one sorted listing the default values but I'm struggling how to write the constructor with three parameters and then get this to call the constructor with four parameters if required.

默认构造函数应该将类型字符串的所有实例变量分配给string.Empty。

The default constructor should assign all instance variables of the type string to string.Empty.

public Address()
{
   m_street = string.Empty;
   m_city = string.Empty;
   m_zipCode = string.Empty;
   m_strErrMessage = string.Empty;
   m_country = Countries;
}


public Address(string street, string city, string zip)
{
}

public Address(string street, string city, string zip, Countries country)
{
}

我正在寻找做以下但是它不工作: -

I was looking to do the following but it doesn't work:-

public Address(string street, string city, string zip)
     : this street, string.Empty, city, string.Empty, zip, string.Empty
{
}


推荐答案

这个想法是将实例化的逻辑留给构造函数,它接受最多的参数,

The idea would be to leave the logic of the instantiation to the constructor that takes in the most parameters and use the others as methods that only pass values to that constructor, that way you only write the code once.

请尝试以下操作:

public Address() 
  : this(String.Empty, String.Empty, String.Empty)
{
}


public Address(string street, string city, string zip) 
  : this(street, city, zip, null)
{
}

public Address(string street, string city, string zip, Countries country) 
{
    m_street = street;
    m_city = city;
    m_zipCode = zip;
    m_country = Countries;
    m_strErrMessage = string.Empty;
}

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

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