“获得”的目的是什么?和“设置” C#中的属性 [英] What is the purpose of the "get" and "set" properties in C#

查看:90
本文介绍了“获得”的目的是什么?和“设置” C#中的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到了一些get set方法来设置值。谁能告诉我这样做的目的吗?

I saw some get set method to set values. Can anyone tell me the purpose of this?

public string HTTP_USER_NAME
{
      get 
      {
            return UserName; 
      }
      set 
      {
            UserName = value; 
      }
}

public string HTTP_USER_PASSWORD
{
      get 
      {
            return UserPwd; 
      }
      set 
      {
            UserPwd = value; 
      }
}

实际上为什么要使用这些东西。对于全局访问,还是这种原因还有其他原因吗?

Actually why use these things. For global access, or is there some other reason for this type of thing?

推荐答案

它们只是访问器和更改器。这就是在C#中实现属性的方式

They are just accessors and mutators. That's how properties are implemented in C#

在C#3中,您可以使用自动实现的属性,如下所示:

In C# 3 you can use auto-implemented properties like this:

public int MyProperty { get; set; }

此代码由编译器自动翻译为类似于您发布的代码,并带有此代码更容易声明属性,如果您不想在 set get 内实现自定义逻辑,它们是理想的选择方法,甚至可以对 set 方法使用其他访问器,以使属性不可变

This code is automatically translated by the compiler to code similar to the one you posted, with this code is easier to declare properties and they are ideal if you don't want to implement custom logic inside the set or get methods, you can even use a different accessor for the set method making the property immutable

public int MyProperty { get; private set; }

在先前的示例中, MyProperty 将只能在声明了它的类之外读取它,对其进行突变的唯一方法是通过公开一个方法来做到这一点,或者仅通过类的构造函数。当您想要控制并明确显示实体的状态更改时,这很有用。

In the previous sample the MyProperty will be read only outside the class where it was declared, the only way to mutate it is by exposing a method to do it or just through the constructor of the class. This is useful when you want to control and make explicit the state change of your entity

当您想向属性添加一些逻辑时,您需要手动编写属性实现 get set 方法,就像您发布的内容一样:

When you want to add some logic to the properties then you need to write the properties manually implementing the get and set methods just like you posted:

实现自定义逻辑的示例

private int myProperty;
public int MyProperty
{
   get
   {
       return this.myProperty;
   }
   set
   {
       if(this.myProperty <=5)
          throw new ArgumentOutOfRangeException("bad user");
       this.myProperty = value;
   }
}

这篇关于“获得”的目的是什么?和“设置” C#中的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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