属性或索引器不能分配给" - "它只读C#List <Tuple <string,bool >>

Pla*_*tus 2 .net c# asp.net-mvc tuples

我创建了以下类:

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; } 
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

但是我收到以下错误消息:

属性或索引器'Tuple.Item2'不能分配给" - "它是只读的.

我怎么解决这个问题?

Dar*_*rov 6

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

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

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


Mak*_*kin 1

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

public class MyTuple
{
   public MyTuple(string item1, bool item2)
   {
     Item1 = item1;
     Item2 = item2; 
   }
   public string Item1 {get;set;}
   public bool Item2 {get;set;}
}
Run Code Online (Sandbox Code Playgroud)

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

public List<MyTuple>> List
Run Code Online (Sandbox Code Playgroud)

并且能够更改 Item1/Item2