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

查看:190
本文介绍了封装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和什么也没有在那里设置, - 这不就是同刚刚宣布您的私人支持字段公开?如果你可以得到和从外部设定,为什么你不只是做它直接?

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



另一件事是,你可以让性能的虚拟

public virtual string Name { get; set; }



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

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

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

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