在C#是什么代码"获得"意思?

问题描述:

我是新的C#

private string m;
public string M { get { return m; } }



这是一种在C#中的getter / setter像Java的?

Is this kind of a getter/setter in C# like Java?

这部分是一个领域:

private string m;

这部分是返回的 m的值一个只读属性字段:

public string M { get { return m; } }

您能做出这样一个读写属性,像这样:

You could make this a read-write property like so:

public string M {
    get { return m; }
    set { m = value; }
}



或者你可以在那里有更复杂的逻辑:

Or you could have more complex logic in there:

public string M {
    get {
        if (string.IsNullOrEmpty(m))
            return "m is null or empty";
        return m;
    }
}



基本上,字段只拿着东西的好,而性能更喜欢的方法和可能引入逻辑。

Basically, fields are only good at holding things, while properties are more like methods and can introduce logic.