如果您只在对象初始化时设置变量,但希望其他对象能够读取该变量而不在初始化后设置它,那么 C# 中的正确语法是什么?
据我了解,它看起来像这样:
class Test
{
private string name;
public string Name { get { return name; } }
public Test() {
this.name = "Hello World!";
}
}
这是正确的方法吗?
这将是正确的方法,但是,您可能需要考虑使用readonly
关键字,因为这可以防止name
在构造函数之外修改变量。
像这样:
class Test
{
private readonly string name;
public string Name { get { return name; } }
public Test()
{
name = "Hello World!";
}
public Test(string name)
{
this.name = name; //You use this to set scope to the object to disambiguate name
}
}
甚至更简单的实现是使用a,readonly automatic property
但这不会阻止在构造函数之外进行修改:
class Test
{
public string Name {get; private set;}
public Test()
{
Name = "Hello World!";
}
public Test(string name)
{
Name = name;
}
}
如果您使用的是 C# 6:
class Test
{
public string Name {get;} = "Hello World!";
public Test()
{
}
public Test(string name)
{
Name = name;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句