我有一个班级
class TestFixture
{
public string a { get; set; }
public int b { get; set; }
public int c { get; set; }
public string d { get; set; }
public string e { get ; set ; }
public int f { get; set; }
public int g { get; set; }
public bool h { get; set; }
public string i { get; set; }
public bool j { get; set; }
public bool k { get; set; }
public TestFixture()
{
e= dosomething(a, b);
f= false;
g = DateTime.Now.ToString("yyMMddhhmmss");
h= TestName.Equals("1") && b.Equals("2") ? 1000 : 1;
i= 10000000;
j= a.Equals("FOT");
k = false;
}
}
我想将新的TestFixture定义为SO
new TestFixture { a = "", b = 1, c=2, d="" };
而其他属性应该在构造函数中自动定义。
有可能吗?
答案 0 :(得分:4)
是的,这是可能的。使用对象初始值设定项不会跳过调用构造函数。
TestFixture fixture = new TestFixture() // or just new TestFixture { ... }
{
a = "",
b = 1,
c = 2,
d = ""
};
这将调用您已定义的构造函数,然后在对象初始值设定项中设置a
,b
,c
和d
。
在构造函数中弹出断点并运行调试器。这应该会告诉你如何以及何时调用代码中的内容。
重构:
public class TestFixture
{
public string a { get; set; }
public int b { get; set; }
public int c { get; set; }
public string d { get; set; }
// dosomething should check for null strings
public string e { get { return dosomething(a, b); } }
public int f { get; set; }
public int g { get; set; }
public bool h
{
get { return TestName.Equals("1") && b.Equals("2") ? 1000 : 1; }
}
public string i { get; set; }
public bool j { get { return a != null && a.Equals("FOT"); } }
public bool k { get; set; }
public TestFixture(string a, int b, int c, string d)
: this()
{
this.a = a;
this.b = b;
this.c = c;
this.d = d;
}
public TestFixture()
{
f = false;
g = DateTime.Now.ToString("yyMMddhhmmss");
i = 10000000;
k = false;
}
}
答案 1 :(得分:1)
@ hunter的answer是正确的,您可以使用对象初始化程序语法,并且在构造函数运行后将设置这些属性。但是,我想指出一些你的代码可能存在的缺陷
public TestFixture()
{
e= dosomething(a, b);
f= false;
g = DateTime.Now.ToString("yyMMddhhmmss");
h= TestName.Equals("1") && b.Equals("2") ? 1000 : 1;
i= 10000000;
j= a.Equals("FOT");
k = false;
}
此代码未设置a
或b
,但您的内容取决于其值(e
,g
,j
)。对象初始化器语法 not 在这里很有用,如果构造函数中的其他值依赖于它们,则必须对这些值具有适当的默认值。
例如,当您编写var obj = new Bar() { A = "foo" };
时,会扩展为
var obj = new Bar(); // constructor runs
obj.A = "Foo"; // a is set
显然,构造函数中查看A
的代码将看不到值"Foo"
。如果你需要它看到这个值,对象初始化策略将无济于事。您需要一个构造函数重载,它将值存储在A
中。
var obj = new Bar("Foo");
答案 2 :(得分:0)
如果我理解正确,您希望在构造函数运行之前使用给定值初始化a,b,c和d属性。不幸的是,这种方式不可能,因为默认构造函数总是在对象初始化器之前运行。 我建议你做这样的事情:
class TestFixture
{
//... properties
public TestFixture()
{
this.init();
}
public TestFixture(string a, int b, int c, string d)
{
this.a = a;
this.b = b;
this.c = c;
this.d = d;
this.init();
}
private void init()
{
e= dosomething(a, b);
f= false;
g = DateTime.Now.ToString("yyMMddhhmmss");
h= TestName.Equals("1") && b.Equals("2") ? 1000 : 1;
i= 10000000;
j= a.Equals("FOT");
k = false;
}
}
这样,您可以在运行其他初始化程序代码之前初始化a,b,c和d属性。