属性或索引器“--”无法分配值,因为它是只读的。C# List<Tuple<string, bool>>

7

I created the following class:

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”无法分配给“--”,因为它是只读的。
我该如何解决这个问题?

4
正如错误提示所示,你不能这样做;元组是不可变的。 - SLaks
3
为什么元组的项是只读的?为什么元组的项是只读的?请参见此处 - stuartd
您可以通过使用只读的Item1和Item2实例属性来检索元组组件的值。MSDN - p.s.w.g
换句话说...错误告诉你不能编辑元组项。你需要创建一个新的。TheVM.List[i].Item2 = new Typle<string, bool>(TheVM.List[i].Item1, (anotherList[i].Item2 == 1)); - Renatas M.
2个回答

11

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

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

话虽如此,我不建议使用元组作为视图模型。


1
如果您需要在创建元组后更改其中的一部分,则不需要使用元组,只需创建自己的类即可:
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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接