문제

I try to assign a value to two different properties in object initializer and failed.

In below code i try to assign Expand and Select properies to true. But i got the error 'The name Select doesnt exist in the current context'

Here is my code

public class MyClass{
public String Title{get;set;}
public String Key{get;set;}
public bool Expand{get;set;}
public bool Select{get;set;}
public bool Editable{get;set;}
}

new MyClass()
  {
   Title = "Murali",
   Key = "MM",                       
   Expand = Select = true
  }

Also i need to assign another property Editable based on this two properties

Something like

new MyClass()
  {
   Ediatable=(Select && Expand)
  }

How can i do the above logic? Does Object Initializer has a support of it?

도움이 되었습니까?

해결책

You cannot refer to properties of the object you're constructing on the right-hand side of a =, i.e., you can only assign to the properties, but not read from them.

Possible solution:

var expandAndSelect = true;

var result = new MyClass
{
    Title = "Murali",
    Key = "MM",                       
    Expand = expandAndSelect,
    Select = expandAndSelect,
};

and

var select = true;
var expand = false;

var result = new MyClass
{
    Expand = expand,
    Select = select,
    Editable = select & expand,
};
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top