简体   繁体   English

如何使用对象初始化器将相同的值分配给不同的属性

[英]How to assign a same value to different properties using Object Initializer

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. 在下面的代码中,我尝试将Expand和Select属性分配为true。 But i got the error ' The name Select doesnt exist in the current context ' 但是我得到了错误“ 名称Select在当前上下文中不存在

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 我还需要基于这两个属性分配另一个属性Editable

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 = , ie, 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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将变量的不同值分配给同一对象的不同实例? - How to assign different values of variables to different instances of the same object? 使用 object 初始化程序时如何向列表添加值? - How to add value to list when using object initializer? 如何使用 LINQ 为实体分配相同的值 - How to assign a same value to entity using LINQ 如何分配在2个不同名称空间中声明的相同类对象 - How to assign same class object declared in 2 different namespaces 使用对象初始化器的附加值是什么? - What is the added value of using object initializer? 如何在对象初始值设定项中分配只读成员变量? - How do I assign a readonly member variable in an object initializer? 使用对象初始化程序初始化对象时添加DataCollection属性 - Add DataCollection properties while Initialize Objects by Using an Object Initializer 如何使用对象的目标类型使用Expression.Assign选择器来一般地分配属性? - How to assign properties generically using Expression.Assign selector with target type of object? 对象初始化程序和动态指定属性 - Object Initializer and Dynamically specifying properties “For”循环 - 使用 PropertyInfo 为属性赋值 - "For" loop - assign value to properties using PropertyInfo
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM