在结构中分配字段/属性

时间:2011-09-02 04:12:52

标签: c# struct variable-assignment

  

可能重复:
  Modify Struct variable in a Dictionary

为什么会这样?

  MyStruct test = new MyStruct();
  test.Closed = true;

效果很好,但是

MyDictionary[key].Closed = true;

在编译时显示“无法修改表达式,因为它不是变量”错误?

为什么这两种情况下的任务有所不同?

注意:MyDictionary的类型为<int, MyStruct>

结构代码:

public struct MyStruct
{
    //Other variables
    public bool Isclosed;
    public bool Closed
    {
        get { return Isclosed; }
        set { Isclosed = value; }
    }
//Constructors
}

2 个答案:

答案 0 :(得分:12)

因为MyDictionary[key]返回一个结构,它实际上是返回集合中对象的副本,而不是实际对象,这是使用类时发生的事情。这就是编译器警告你的内容。

要解决此问题,您必须重新设置MyDictionary[key],或许会这样:

var tempObj = MyDictionary[key];
tempObj.Closed = true;
MyDictionary[key] = tempObj;

答案 1 :(得分:1)

将结构更改为类而不是......

class Program
{
    static void Main(string[] args)
    {
        dic = new Dictionary<int, MyStruct>();

        MyStruct s = new MyStruct(){ Isclosed=false};

        dic.Add(1,s);

        dic[1].Isclosed = true;

        Console.WriteLine(dic[1].Isclosed.ToString()); //will print out true...
        Console.Read();
    }

    static Dictionary<int, MyStruct> dic;

    public class MyStruct
    {
        public bool Isclosed;
        public bool Closed
        {
            get { return Isclosed; }
            set { Isclosed = value; }
        }
    }
}