C#快捷方式表示法创建类实例

时间:2011-05-10 03:02:59

标签: c# constructor shortcut instantiation

我确信有一种方法可以轻松创建一个类的实例,但我对伟大的interwebs的搜索还没有找到它。让我说我有这个:

List<LicencedCustomer> leftList = new List<LicencedCustomer>();

leftList.Add(new LicencedCustomer (LMAA_CODE:"1",LICENSE_NUMBER:"1",TRADING_NAME:"Bobs Liquor",STATE:"NSW",POSTCODE:"2261"));

我的课程如下所示。

public class LicencedCustomer
{

    public string LMAA_CODE {get; set;}
    public string LICENSE_NUMBER {get; set;}
    public string TRADING_NAME {get; set;}
    public string STATE  {get; set;}
    public string POSTCODE  {get; set;}

    public LicencedCustomer(string LMAA_CODE, string LICENSE_NUMBER, string TRADING_NAME, string STATE, string POSTCODE)
    {
        this.LMAA_CODE = LMAA_CODE;
        this.LICENSE_NUMBER = LICENSE_NUMBER;
        this.TRADING_NAME = TRADING_NAME;
        this.STATE = STATE;
        this.POSTCODE = POSTCODE;
    }

    ...

如果没有上面的构造函数,我会收到一个错误,即该类不包含带有5个参数的构造函数(最初我只使用了值而没有使用List.Add函数中的字段名称)。

是否有一个快捷方式允许在创建时分配属性,而无需显式定义构造函数?

谢谢!

编辑:广泛的好奇心源于大写的属性 - 它们只是这样,因为它们是为了反映导入文件的标题而构建的。不是我喜欢的方法!

2 个答案:

答案 0 :(得分:4)

添加默认构造函数,然后尝试类似:

new LicencedCustomer() { LMAA_CODE = ..., LICENSE_NUMBER = ..., ... };

附注:大写属性并不常见。

答案 1 :(得分:4)

使用new()时,调用与参数匹配的构造函数。如果没有已定义的构造函数,则会得到一个隐式参数less constructor。

要使用快捷方式初始化程序,请使用类似的内容。

public class sCls
{
    public int A;
    public string B;

}
static void Main(string[] args)
{
   sCls oCls = new sCls() {A = 4, B = "HI"};
}

修改


如果您添加一个带有参数的consturctor,则从注释中删除了implict无参数构造函数

public class sCls
{
    public sCls(string setB)
    {
        B = setB;
    }
    public int A;
    public string B;

}
static void Main(string[] args)
{
    sCls oCls = new sCls() {A = 4, B = "HI"}; // ERROR  error CS1729: 'csCA.Program.sCls' does not contain a constructor that takes 0 arguments
}

您还可以将任何构造函数与初始化列表

一起使用
public class sCls
{
    public sCls(string setB)
    {
        B = setB;
    }
    public int A;
    public string B;

}
static void Main(string[] args)
{
    sCls oCls = new sCls("hi") {A = 4, B = "HI"};
}

请记住,在所有情况下,构造函数都在初始化列表之前调用,即使它具有参数less constructor。因此,基类构造或在对象构造中发生的任何其他事情都将首先发生。

    public class BSE
    {
        public BSE()
        {
            BaseA = "Bob";
        }
        public string BaseA;
    }
    public class sCls :BSE
    {

        public int A;
        public string B;

    }
static void Main(string[] args)
{
        sCls oCls = new sCls() {A = 4, B = "HI" };
        Console.WriteLine("{0}", oCls.BaseA);//Prints Bob
}
相关问题