在C#是什么代码"获得"意思? [英] In C# what does this code with "get" mean?

查看:161
本文介绍了在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.

这篇关于在C#是什么代码"获得"意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆