【问题标题】:Property or indexer cannot be assigned to “--” it is read only C# List<Tuple<string, bool>>属性或索引器不能分配给“--”它是只读的 C# List<Tuple<string, bool>>
【发布时间】:2017-01-30 15:29:38
【问题描述】:

我创建了以下类:

namespace Prototype.ViewModel.MyVM
{
    public clas TheVm
    {
        List<Tuple<string, bool>> list = new List<Tuple<string, bool>>();
        public List<Tuple<string, bool>> List 
        { 
            get { return this.list; } 
            set { this.list = value; } 
        }
    }
}

在另一个代码文件中,我正在尝试修改封装的 List> 对象的值之一:

for (int i = 0; i < anotherList.Count; i++)
{
    TheVM.List[i].Item2 = (anotherList[i].Item2 == 1);
}

但我收到以下错误消息:

属性或索引器“Tuple.Item2”不能分配给“--”,它是只读的。

我该如何解决?

【问题讨论】:

  • 错误试图告诉你,你不能那样做;元组是不可变的。
  • MSDN: "您可以使用 只读 Item1 和 Item2 实例属性检索元组组件的值。"
  • 换句话说...错误告诉你不能编辑元组项。你需要创建一个新的。 TheVM.List[i].Item2 = new Typle&lt;string, bool&gt;(TheVM.List[i].Item1, (anotherList[i].Item2 == 1));

标签: c# .net asp.net-mvc tuples


【解决方案1】:

您需要创建一个新的元组,因为它们是不可变的:

for (int i = 0; i < anotherList.Count; i++)
{
    TheVM.List[i] = new Tuple<string, bool>(TheVM.List[i].Item1, anotherList[i].Item2 == 1);
}

话虽如此,我建议不要将元组用于视图模型。

【讨论】:

    【解决方案2】:

    如果创建后需要更改元组的一部分,则不需要元组,只需创建自己的类即可:

    public class MyTuple
    {
       public MyTuple(string item1, bool item2)
       {
         Item1 = item1;
         Item2 = item2; 
       }
       public string Item1 {get;set;}
       public bool Item2 {get;set;}
    }
    

    之后,您可以将您的列表定义为:

    public List<MyTuple>> List
    

    并且将能够更改 Item1/Item2

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-03
      • 2019-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多