获得在C#中的哪一套方法的目的 [英] Get Set methods purpose of what in C#

查看:127
本文介绍了获得在C#中的哪一套方法的目的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到一些获取设置的方法来设置值。谁能告诉我这样做的目的是什么?

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

这code是由编译器为code类似于你贴一个自动翻译,这个code更容易声明属性,他们是理想的,如果你不想来实现自定义里面的逻辑设置 GET 方法,你甚至可以使用的设置不同的访问方法使得性能不变

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

在previous品尝 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 设置方法,就像你贴:

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:

例如,实现自定义的逻辑

Example implementing custom logic

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天全站免登陆