如何同时声明和填充类

时间:2011-11-21 11:30:39

标签: c# c#-4.0

我有这样的代码:

public class test {
    public string aa { get; set; }
    public string bb { get; set; }
    public string cc { get; set; }
}

var a = new test {
    aa = "a",
    bb = "b"
}

var d = a;
d.cc = "c";

有没有办法让我创建d类并同时填充它。那么例如最后两行可以组合成一个?请注意,我希望避免使用构造函数执行此操作,因为有时我将填充不同于cc的字段。

请注意我的编辑

var d = a;

4 个答案:

答案 0 :(得分:3)

您可以采用与a相同的方式:

var d = new test {
    cc = "c"
}

此语法,使用构造函数传入参数,但称为object initializer

每当从类创建新对象时,都会调用构造函数。没有办法避免这种情况。


更新

现在你想要做的更清楚了,前进的方法是使用copy constructor并将其作为新对象的基础:

public class test {

    public test(test o)
    {
      aa = o.aa;
      bb = o.bb;
    }

    public string aa { get; set; }
    public string bb { get; set; }
    public string cc { get; set; }
}

var a = new test {
    aa = "a",
    bb = "b"
}

var d = new test(a) {cc = "c"};

答案 1 :(得分:3)

此行不符合要求:

var d = test;

初始化程序仅在装箱对象时才有效,所以在您的情况下,仅在此时:

var d = new test {
    cc = "c"
}

关于初始化程序的Msdn Doc:http://msdn.microsoft.com/en-us/library/bb384062.aspx

答案 2 :(得分:0)

您可以为类创建构造函数并传入所需的值

//Class constructor
public Test(string aa, string bb, string cc) 
{
    this.aa = aa;
    ...
}




var test = new Test("a","b","c")

答案 3 :(得分:0)

鉴于您对该问题的新描述,如何:

请注意,它也会更改a(与您的代码相同),不会创建副本。如果你想要一份副本,请使用Oded的解决方案。

public class test
{
    public string aa { get; set; }
    public string bb { get; set; }
    public string cc { get; set; }

    public test AlterTest(Action<test> alteration)
    {
        alteration(this);
        return this;
    }
}

static void Main(string[] args)
{
    var a = new test
    {
        aa = "a",
        bb = "b"
    };

    var d = a.AlterTest((t) => t.cc = "c");
}

我会说这不像你的原始代码那么可读(因为你需要知道AlterTest做了什么,这不是很多)。