开发者

In C# what does this code with "get" mean?

I am new to开发者_如何学编程 C#.

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

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


This part is a field:

private string m;

This part is a read-only property that returns the value of the m field:

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.


private string m;

First, you create a new string variable with private modifier. If this in class, then it's not visible outside of this class.

public string M { get { return m; } }

Then you create a property of that string variable. This property is read-only and then you can access this variable outside of class where you created this variable. You cannot assign values to this variable with this type of property.


It's a public readonly property, i.e.: it only has a public get accessor. Auto-implemented properties can achieve the same effect with less code:

public string M { get; private set; }

This propery has a public get but a private set. The CLR actually generates an m-like field for storing the value... but it's hidden.


It's a getter. There is no publically accessible setter, so m must be set elsewhere in the class.


This is for defining Readonly properties in C#, here you only have a getter


It is a public getter for m, but it lets you call it like it was a variable for example

string s = M;

which would make s == m


This is what is called a property in C#. It is accessed as if it was a member variable, but the get method is called instead. Properties can also have a set method, to make them modifiable.


The first line is called a field. It will create a private (i.e. accessible only within the class) member variable named m.

The second line is called a property. This particular property wraps the field m and is read-only (i.e. it has a get but no set).

Properties in C# are accessed as if they are fields, like so:

obj.SomeProp = "Some value";
string val = obj.SomeProp;

However, properties can be implemented with more complexity than just getting and setting a field. The body of the property is like a method. It can contain non-trivial code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜