3

由于“a”是键入的值,我有以下代码不起作用。但我认为即使没有访问器它也不会工作,但它确实:

class Program
    {
        a _a  //with accessors it WONT compile
        {
            get; 
            set;
        }
        static void Main(string[] args)
        {
            Program p = new Program();
            p._a.X = 5; //when both accessors are deleted, compiler does not
                        //complain about _a.X not being as variable
        }
    }
    struct a
    {
       public int X;
    }

它不起作用,因为“a”是结构。但是当我从“_a”实例中删除访问器时,它可以工作。我不懂为什么。谢谢

4

3 回答 3

2

The main feature of value types is that they are copied rather than being passed by reference.

When you have a value type, and an accessor, you essentially have a value type being returned from a method, which causes a copy (the following two examples are the same):

ValueType Property { get { return x; } } // Will make a copy of x
ValueType Method() { return x; }    // Will make a copy of x

If you now assign to the returned value, you're assigning to a copy of x. So any changes made to the value returned from the property will be immediately lost.

When you remove the { get; } accessor, you've now got a basic field, e.g.:

int field;

or

ValueType field;

Which means no copy is made, which means when assigning to the field, you're no longer assigning to a copy.

于 2010-04-07T08:46:06.783 回答
1

您不能同时删除这两个访问器。

这边走:

a _a;

它有效,但它不再是一个属性。


编辑:使用属性,您从 p._a 获得的值是函数调用的结果。即使你修改它,修改后的值也绝不会“写回”到“原始” _a。相反,您只需修改由 getter 函数返回的临时值。

C# 可以允许这样做,但它会导致混乱,因为人们会期望值之后p._a.X = 5; int xx = p._a.X;xx是 5。但事实并非如此。因为 p_.a 确实不是变量:-)


不同的是,与

a _a;

_a是一个领域;的情况下

a _a { get; set; }

_a是一个属性。而案件

a _a { }

不被允许。

于 2010-04-07T08:33:14.423 回答
1

The reason p._a.X = 5; won't work is because p._a returns a value of the type a. Values cannot change. But if you put the value in a variable, you may change the value of the variable.

于 2010-04-07T08:46:45.913 回答