简体   繁体   English

C#中“ get”和“ set”属性的用途是什么

[英]What is the purpose of the “get” and “set” properties in C#

I saw some get set method to set values. 我看到了一些get set方法来设置值。 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? 对于全局访问,还是这种原因还有其他原因吗?

They are just accessors and mutators. 它们只是访问器和更改器。 That's how properties are implemented in C# 这就是在C#中实现属性的方式

In C# 3 you can use auto-implemented properties like this: 在C#3中,您可以使用自动实现的属性,如下所示:

public int MyProperty { 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 该代码由编译器自动翻译为与您发布的代码类似的代码,该代码更易于声明属性,如果您不想在setget方法中实现自定义逻辑,它们是理想的选择,甚至可以使用set方法的另一个访问器,使属性不可变

public int MyProperty { get; private set; }

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. 在前面的示例中, MyProperty将仅在声明它的类之外读取,对其进行更改的唯一方法是通过公开执行该操作的方法或仅通过该类的构造函数。 This is useful when you want to control and make explicit the state change of your entity 当您要控制并明确显示实体的状态更改时,这很有用

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: 当您想向属性添加一些逻辑时,您需要手动编写属性,就像您发布的那样实现getset方法:

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

It seems as though you understand the functionality of getters and setters, and others answered that question. 好像您了解getter和setter的功能,其他人回答了这个问题。 "Normal" class variables (without getters and setters) are called "fields", and "properties" (which have the getters and setters) encapsulate fields. “普通”类变量(无getter和setter)称为“字段”,“ properties”(具有getter和setter)封装字段。

The purpose of properties is to control outside access to fields. 属性的目的是控制外部对字段的访问。 If you want a variable to be read-only to outside logic, you can omit the setters, like so: 如果希望变量对外部逻辑只读,则可以省略设置器,如下所示:

private int dataID;

public int DataID {
    get { return dataID; }
}

You can also make the setter private and achieve the same read-only functionality. 您还可以将设置器设为私有,并实现相同的只读功能。

If an object has a chance of being null (for whatever reason), you can guarantee an instance always exists like this: 如果某个对象有可能为空(无论出于何种原因),则可以保证实例始终存在,如下所示:

private Object instance;

public Object Instance {
    get {
        if (instance == null)
            instance = new Object();
        return instance;
    }
}

Another use for properties is defining indexers. 属性的另一个用途是定义索引器。

//in class named DataSet

private List<int> members;

public int this[int index] {
    get { return members[index]; }
}

With that indexer defined, you can access an instance of DataSet like this: 定义了该索引器之后,您可以访问DataSet的实例,如下所示:

int member = dataSet[3];

Check these links,.. they gives clear explanation. 检查这些链接,..它们给出明确的解释。

http://www.dotnetperls.com/property http://www.dotnetperls.com/property

http://code.anjanesh.net/2008/02/property-getters-setters.html http://code.anjanesh.net/2008/02/property-getters-setters.html

if UserName and UserPwd are class variables, better to use like this 如果UserName和UserPwd是类变量,则最好像这样使用

_userName 
_userPwd

Standard way to implement properties in C# . 在C#中实现属性的标准方法。 UserName and UserPwd are private member variables ( string type) of the class where these 2 methods are defined. UserNameUserPwd是定义了这两种方法的类的私有成员变量( string类型)。

HTTP_USER_NAME and HTTP_USER_PASSWORD are the public properties of your class. HTTP_USER_NAMEHTTP_USER_PASSWORD是您的课程的公共属性。 UserName and UserPwd could be your private field. UserNameUserPwd可以是您的私有字段。 And you are allowing other people to set or get the values via these public properties. 并且您允许其他人通过这些公共属性来设置或获取值。 No direct accesss to private propeties. 不能直接接触私人财产。 Also you can do some logic inside the get method of the property.Ex : you will have a public property called Age and in the get method of that, you may read the value of your private field called " dateOfBirth " and do some calculation ( CurrentYear-dateOfBirth) and return that as the Age. 同样,您可以在property的get方法中进行一些逻辑处理。例如:您将拥有一个名为Age的公共属性,在该方法的get方法中,您可以读取私有字段“ dateOfBirth ”的值并进行一些计算( CurrentYear-dateOfBirth),并将其返回为Age。

Properties are just accessors over fields. 属性只是字段的访问器。 They allow to do certain operations (if needed), and provide controlled access to fields. 它们允许执行某些操作(如果需要),并提供对字段的受控访问。

If you want to know when to use Properties, and when to use Only fields, Check the link Properties vs Fields – Why Does it Matter? 如果您想知道何时使用属性以及何时仅使用字段,请检查链接“ 属性与字段” –为什么如此? (Jonathan Aneja) (乔纳森·阿内贾)

From Properties (C# Programming Guide) 属性(C#编程指南)

A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field. 属性是提供灵活机制以读取,写入或计算私有字段的值的成员。 Properties can be used as if they are public data members, but they are actually special methods called accessors. 可以将属性当作公共数据成员使用,但实际上它们是称为访问器的特殊方法。 This enables data to be accessed easily and still helps promote the safety and flexibility of methods. 这使数据易于访问,并且仍然有助于提高方法的安全性和灵活性。

In this example, the TimePeriod class stores a time period. 在此示例中, TimePeriod类存储一个时间段。 Internally the class stores the time in seconds, but a property named Hours enables a client to specify a time in hours. 在内部,该类以秒为单位存储时间,但是名为Hours的属性使客户端可以以Hours为单位指定时间。 The accessors for the Hours property perform the conversion between hours and seconds. Hours属性的访问器在小时和秒之间执行转换。

Example

class TimePeriod
{
    private double seconds;

    public double Hours
    {
        get { return seconds / 3600; }
        set { seconds = value * 3600; }
    }
}


class Program
{
    static void Main()
    {
        TimePeriod t = new TimePeriod();

        // Assigning the Hours property causes the 'set' accessor to be called.
        t.Hours = 24;

        // Evaluating the Hours property causes the 'get' accessor to be called.
        System.Console.WriteLine("Time in hours: " + t.Hours);
    }
}
// Output: Time in hours: 24

Properties Overview 属性概述

  • Properties enable a class to expose a public way of getting and setting values, while hiding implementation or verification code. 属性使类可以公开获取和设置值的公共方式,同时隐藏实现或验证代码。

  • A get property accessor is used to return the property value, and a set accessor is used to assign a new value. 获取属性访问器用于返回属性值,而设置访问器用于分配新值。 These accessors can have different access levels. 这些访问器可以具有不同的访问级别。 For more information, see Restricting Accessor Accessibility (C# Programming Guide) . 有关更多信息,请参见限制访问者可访问性(C#编程指南)

  • The value keyword is used to define the value being assigned by the set accessor. value关键字用于定义由set访问器分配的值。

  • Properties that do not implement a set accessor are read only. 未实现集合访问器的属性是只读的。

  • For simple properties that require no custom accessor code, consider the option of using auto-implemented properties. 对于不需要自定义访问器代码的简单属性,请考虑使用自动实现的属性的选项。 For more information, see Auto-Implemented Properties (C# Programming Guide) . 有关更多信息,请参见自动实现的属性(C#编程指南)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM