封装 C# 新手 [英] Encapsulation C# newbie

查看:29
本文介绍了封装 C# 新手的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C# 新手,我明白封装只是保护数据"的一种方式.但我还是不清楚.我认为 get 和 set 访问器的要点是在这些方法中添加测试以检查参数是否满足特定条件,然后再允许外部函数获取和设置任何内容,如下所示:>

New to C#, and I understand that encapsulation is just a way of "protecting data". But I am still unclear. I thought that the point of get and set accessors were to add tests within those methods to check to see if parameters meet certain criteria, before allowing an external function to get and set anything, like this:

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;
        }

    } 
}

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

But I've been seeing code in c# which just looks like this:

public string MyName { get; set; }

为什么你只需要一个 get 和 set 里面什么都没有, - 这不是和只是宣布你的私人支持领域是公开的一样吗?如果你可以直接从外面获取和设置它,你为什么不直接做?

Why would you just have a get and set with nothing in there, - isn't that the same as just declaring your private backing field public? If you can just get and set it from outside, why wouldn't you just do it directly?

推荐答案

确实,创建一个自动属性如下:

Indeed, creating an auto-property as follows:

public string Name { get; set; }

与构建由字段支持的属性相同:

is identical to building a property backed by a field:

private string _name;
public string Name {
    get { return _name; }
    set { _name = value; }
}

这些属性的目的不是隐藏数据.正如你所观察到的,他们不这样做.相反,这些属性可以做其他事情,而不仅仅是处理一个字段:

The point of these properties is not to hide data. As you observed, they don't do this. Instead, these properties can do other stuff instead of just working with a field:

public string Name {
    get { return _name; }
    set { if (value == null) throw new Exception("GTFO!"); _name = value; }
}

另一件事是,您可以使属性虚拟:

Another thing is, you can make properties virtual:

public virtual string Name { get; set; }

如果被覆盖,可以在派生类中提供不同的结果和行为.

which, if overridden, can provide different results and behaviours in a derived class.

这篇关于封装 C# 新手的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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