小编Gia*_*ani的帖子

封装C#newbie

C#的新手,我知道封装只是一种"保护数据"的方式.但我还不清楚.我认为 get和set访问的是增加这些方法中的测试,以检查是否参数满足一定条件,允许外部函数来获取和设置任何东西,这样才:

private string myName;
public string MyName;// this is a property, speical to c#, which sets the backing field.

private string myName = "mary";// the backing field.

public string MyName // this is a property, which sets/gets the backing field.
{
    get
    {
        return myName;
    }
    set
    {
        if (value != "Silly Woman"){ 
           myName = value;
        }

    } 
}
Run Code Online (Sandbox Code Playgroud)

但是我一直在看c#中的代码看起来像这样:

public string MyName { get; set; }
Run Code Online (Sandbox Code Playgroud)

为什么你只是在那里得到一个没有任何东西的get-set, - 这不仅仅是公开你的私人支持领域吗?如果您可以从外部获取并设置它,为什么不直接进行?

c# encapsulation get set

3
推荐指数
1
解决办法
3154
查看次数

标签 统计

c# ×1

encapsulation ×1

get ×1

set ×1