从对象初始化程序访问属性
我有以下Person
类
class Person { public string FirstName { get; set; } public string LastName { get; set; } public string FullName { get { return FirstName + " " + LastName; } } public IEnumerable Children { get; set; } }
我可以像这样初始化它:
Person p = new Person() { FirstName = "John", LastName = "Doe" };
但是有可能在对象初始值设定项中引用Person
另一个属性,所以我可以这样做吗?
Person p = new Person() { FirstName = "John", LastName = "Doe", Children = GetChildrenByFullName(FullName); };
编辑
出于问题的原因,引用的属性不必根据其他属性计算,但其值可以在构造函数中设置。
谢谢
你不能这样做:
void Foo() { String FullName = ""; Person p = new Person() { FirstName = "John", LastName = "Doe", Children = GetChildrenByFullName(FullName); // is this p.FullName // or local variable FullName? }; }
不在内部对象初始化器中时,您不在该类的实例中。 换句话说,您只能访问可以设置的公开公开属性。
明确:
class Person { public readonly string CannotBeAccessed; public string CannotBeAccessed2 {get;} public void CannotBeAccessed3() { } public string CanBeAccessed; public string CanBeAccessed2 { set; } }
我认为您可以通过使用私有局部变量支持您的属性来解决您的问题。 例如
class Person { private string m_FirstName = string.Empty; private string m_LastName = string.Empty; public string FirstName { get { return m_FirstName; } set { m_FirstName = value; } } public string LastName { get { return m_LastName; } set { m_LastName = value;} } public string FullName { get { return m_FirstName + " " + m_LastName; } } public IEnumerable Children { get; set; } }
假设对象初始化程序按照您在初始化代码中指定它们的顺序设置属性(并且它应该),则局部变量应该是可访问的(在FullName readonly属性内部)。