Accessing properties from object initializer [duplicate]

僤鯓⒐⒋嵵緔 提交于 2019-12-17 20:52:01

问题


I have the following Person class

class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string FullName
    {
        get { return FirstName + " " + LastName; }
    }
    public IEnumerable<Person> Children { get; set; }
}

I could initialize it like this:

Person p = new Person() { FirstName = "John", LastName = "Doe" };

But is it possible to reference another property of Person in the object initializer, so I could do for example something like this?

Person p = new Person()
{
    FirstName = "John",
    LastName  = "Doe",
    Children  = GetChildrenByFullName(FullName);
};

EDIT

For the sake of the question, the referenced property doesn't have to be calculated according to other properties, but its value could be set in the constructor.

Thanks


回答1:


You can't do that:

void Foo()
{ 
  String FullName = "";

  Person p = new Person()
  {
    FirstName = "John",
    LastName  = "Doe",
    Children  = GetChildrenByFullName(FullName); // is this p.FullName 
                                                 // or local variable FullName?
  };
}



回答2:


No. When inside the object initialiser, you are not inside an instance of the class. In other words, you only have access to the publicy exposed properties that can be set.

Explicitly:

class Person
{
    public readonly string CannotBeAccessed;
    public  string CannotBeAccessed2 {get;}
    public void CannotBeAccessed3() { }

    public string CanBeAccessed;
    public string CanBeAccessed2 { set; }
} 



回答3:


I think that you may be able to solve your problem by backing your properties with private local variables. e.g.

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<Person> Children { get; set; }
}

Assuming the object initializer sets the properties in the order that you specify them in the initialization code (and it should), the local variables should be accessable (internally by the FullName readonly property).



来源:https://stackoverflow.com/questions/11859553/accessing-properties-from-object-initializer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!