访问器的目的是什么?

发布于 2024-11-17 22:14:08 字数 84 浏览 4 评论 0原文

有人可以帮助我理解 get & 吗? 设置
为什么需要它们?我可以创建一个公共变量。

Can somebody help me understand the get & set?
Why are they needed? I can just make a public variable.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

愛放△進行李 2024-11-24 22:14:08

警告:我假设您已经了解面向对象编程

什么是属性?

属性是语言元素,可让您避免在其他语言(如 Java)中使用重复的 getXYZ() 访问器和 setXYZ() 变异器技术。

它们为何存在?

他们的目标是解决以下问题:

  1. 在每次访问或改变值的开始时说 getset 很烦人和分散注意力。

    在Java中,你经常说:

    类人
    {
        私有 int _age;
        public void setAge(int value) { /*先检查值,然后设置_age*/ }
        公共 int getAge() { 返回 this._age; }
    }
    

    然后不断地说:

    if (person.getAge() > blah || person.getAge() < 10)
    {
        人.setAge(5);
    }
    

    过了一会儿,getset变得相当烦人。

  2. 提供对实际变量的直接访问会破坏封装,因此这不是一个选项。

它们是如何使用的?

它们使用就像变量。您可以像变量一样读取/写入它们。

它们是如何创建的?

它们被创建为方法。您定义一对方法:

  1. 返回属性的当前值。通常,这无非是如下所示:

    类 Person
    {
        私有 int _age; //声明支持字段
    
        公共整数年龄
        {
            获取 { 返回 this._age; }
            放 { ... }
        }
    }
    
  2. 设置属性的值:

    类 Person
    {
        公共整数年龄
        {
            得到 { ... }
            放
            {
                if (value < 0) //'value'是用户提供的
                { 抛出新的 ArgumentOutOfRangeException(); } //检查有效性
                this._age = 值;
            }
        }
    }
    

其他说明:

自动实现的属性

C# 3.0 引入了自动实现的属性:

public int Age { get; set; }

这相当于:

private int _age; //The name is auto-generated
public int Age { get { return this._age; } set { this._age = value; } }

为什么它存在?

它可以帮助您避免对客户端可执行文件进行重大更改

假设您很懒,不想输入整个内容,并决定公开公开一个变量。然后,您创建一个读取或写入该字段的可执行文件。然后你改变主意并决定你实际上需要一处房产,因此你将其更改为一处。

会发生什么?

依赖的可执行文件会中断,因为代码不再有效。

自动实现的属性可以帮助您避免这种情况,而无需在初始代码中出现额外的冗余。

索引器

索引器扩展了属性语法,让您可以为对象建立索引(令人惊讶!),就像数组一样。
对于 C++ 用户:这类似于重载operator []

示例:

private int[] _elements;

public int this[int index] //Indexed property
{
    get { return this._elements[index]; }
    set
    {
        //Do any checks on the index and value
        this._elements[index] = value;
    }
}

然后像 obj[5] = 10; 一样使用它们,这相当于调用 obj 索引器的 set 方法。
事实上,System.Collections.Generic.List 已建立索引:

var list = new List<int>();
list.Add(10);
list[0] = 5;  //You're indexing list, as though it were an array!

这不是很简洁吗? :)

还要别的吗?

属性还有更多功能,但并非所有功能都在 C# 中可用:

  • 参数化属性,其中索引器是一种特殊类型
  • Getter/setter 访问修饰符(在 C# 中)
  • 多个 getter 或 setter(C# 中没有)
  • 等等

Warning: I am assuming you already know about object-oriented programming.

What are properties?

Properties are language elements that allow you to avoid the repetitive getXYZ() accessors and setXYZ() mutators techniques found in other languages, like Java.

Why do they exist?

They aim to solve the following problems:

  1. Saying get and set in the beginning of every access or mutation of a value is annoying and distracting.

    In Java, you often say:

    class person
    {
        private int _age;
        public void setAge(int value) { /*check value first, then set _age*/ }
        public int getAge() { return this._age; }
    }
    

    and then consistently say:

    if (person.getAge() > blah || person.getAge() < 10)
    {
        person.setAge(5);
    }
    

    After a while, the get and set become rather annoying.

  2. Providing direct access to the actual variable breaks encapsulation, so that's not an option.

How are they used?

They are used just like variables. You read/write to them just like variables.

How are they created?

They are created as methods. You define a pair of methods that:

  1. Return the current value of the property. Oftentimes, this is nothing more than something like the following:

    class Person
    {
        private int _age; //Declare the backing field
    
        public int Age
        {
            get { return this._age; }
            set { ... }
        }
    }
    
  2. Set the value of the property:

    class Person
    {
        public int Age
        {
            get { ... }
            set
            {
                if (value < 0) //'value' is what the user provided
                { throw new ArgumentOutOfRangeException(); } //Check validity
                this._age = value;
            }
        }
    }
    

Other notes:

Auto-implemented Properties

C# 3.0 introduced auto-implemented properties:

public int Age { get; set; }

This is equivalent to:

private int _age; //The name is auto-generated
public int Age { get { return this._age; } set { this._age = value; } }

Why does it exist?

It helps you avoiding breaking changes in client executables.

Let's say you're lazy and don't want to type the whole thing, and decide to expose a variable publicly. You then create an executable that reads from or writes to that field. Then you change your mind and decide that you in fact needed a property, so you change it to one.

What happens?

The depending executable breaks, because the code is no longer valid.

Auto-implemented properties help you avoid that, without extra redundancy in your initial code.

Indexers

Indexers extend the property syntax to let you index objects (surprise!), just like arrays.
For C++ users: This is similar to overloading operator [].

Example:

private int[] _elements;

public int this[int index] //Indexed property
{
    get { return this._elements[index]; }
    set
    {
        //Do any checks on the index and value
        this._elements[index] = value;
    }
}

You then use them like obj[5] = 10;, which is equivalent to calling the set method of obj's indexer.
In fact, System.Collections.Generic.List<T> is indexed:

var list = new List<int>();
list.Add(10);
list[0] = 5;  //You're indexing list, as though it were an array!

Isn't that neat? :)

Anything else?

There are many more features to properties, not all of which are available in C#:

  • Parametrized properties, of which indexers are a special kind
  • Getter/setter access modifiers (in C#)
  • Multiple getters or setters (not in C#)
  • Et cetera
俯瞰星空 2024-11-24 22:14:08

它们被称为访问器

属性的访问器包含与获取(读取或计算)或设置(写入)属性相关的可执行语句。访问器声明可以包含 get 访问器、set 访问器或两者。
get 访问器的主体类似于方法的主体。它必须返回属性类型的值。

http://msdn.microsoft.com/en-us/library/w86s7x04.aspx

private string m_Name;   // the name field
public string Name   // the Name property
{
   get 
   {
      return m_Name; 
   }
}

set 访问器类似于返回类型为 void 的方法。它使用一个名为 value 的隐式参数,其类型是属性的类型。

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

然后,在 C# 3 的化身中,您可以通过自动属性

public string Name {get; set; } // read and write
public string Name {get; }  // read only
public string Name { get; private set; } //read and parent write

​​http 更轻松地完成此操作://msdn.microsoft.com/en-us/library/bb384054.aspx

They are called Accessors

The accessor of a property contains the executable statements associated with getting (reading or computing) or setting (writing) the property. The accessor declarations can contain a get accessor, a set accessor, or both.
The body of the get accessor resembles that of a method. It must return a value of the property type.

http://msdn.microsoft.com/en-us/library/w86s7x04.aspx

private string m_Name;   // the name field
public string Name   // the Name property
{
   get 
   {
      return m_Name; 
   }
}

The set accessor resembles a method whose return type is void. It uses an implicit parameter called value, whose type is the type of the property.

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

Then in the incarnation of C# 3, you can do this much easier through auto-properties

public string Name {get; set; } // read and write
public string Name {get; }  // read only
public string Name { get; private set; } //read and parent write

http://msdn.microsoft.com/en-us/library/bb384054.aspx

饮湿 2024-11-24 22:14:08

属性充当对象内部状态的访问器隐藏该状态的实现

因此,例如,您在类中可能有一个名字属性

public class Example
{
    private string firstName;

    public string FirstName
    {
        get {return this.firstName;}
    }
}

,因此使用该类的任何人都不需要知道如何存储名字,他们只知道可以获得它的字符串表示形式。通过添加一个集合,您还可以添加一个变异器,它可以更改对象内部状态。

public class Example
{
    private string firstName;

    public string FirstName
    {
        get {return this.firstName;}
        set {set this.firstName = value;}   
    }
}           

同样,您仍然隔离第一个名称在内部的存储方式(封装),但是用户可以通过传入字符串来更改它。

Properties act as accessors to the internal state of an object, hiding the implementation of that state.

So, for example, you may have a first name property in a class

public class Example
{
    private string firstName;

    public string FirstName
    {
        get {return this.firstName;}
    }
}

So anyone using the class doesn't need to know how first name is stored, they just know they can get a string representation of it. By adding a set you also add a mutator, something which changes an objects internal state

public class Example
{
    private string firstName;

    public string FirstName
    {
        get {return this.firstName;}
        set {set this.firstName = value;}   
    }
}           

Again you're still isolating how the first name is stored internally (encapsulation), but users can change it by passing in a string.

七秒鱼° 2024-11-24 22:14:08

简单地说,getset 访问器是在属性上调用的函数;也就是说,当您检索该值或设置该值时。它在检索或设置值的方式上强制执行一种行为。

例如,您可能希望有一种获取/设置密码的机制。一般来说,您只想比较密码的散列,而不是存储明文内容,因此您可以让 getter 变量检索存储的散列,而 setter 会获取提供的输入并将其散列以进行存储。

我的意思是:

public class User {
    //Usery properties here, and...
    private string _password;
    public string Password {
        get {
            return _password;
        }
        set {
            _password = SomeHashingFunction(value);
        }
    }
}

value 是根据变量赋值中给出的内容提供给设置器的变量。例如:someuser.Password = "blah";

Simply put, get and set accessors are the functions called on a Property; that is, when you retrieve the value or when you set it. It forces a type of behavior on the way values are retrieved or set.

For example, you may want to have a mechanism to get/set passwords. Generally speaking, you'll only want to compare the hash of a password instead of storing things plaintext, so you'd have the getter variable retrieve the stored hash, and the setter would take the provided input and hash it for storage.

Here's what I mean:

public class User {
    //Usery properties here, and...
    private string _password;
    public string Password {
        get {
            return _password;
        }
        set {
            _password = SomeHashingFunction(value);
        }
    }
}

value is the variable provided to the setter from what has been given in the variable assignment. e.g.: someuser.Password = "blah";

旧人九事 2024-11-24 22:14:08

Get 和 Set 用于属性。它们可以是公共的、受保护的或私有的。与访问器和修改器方法类似,当代码尝试访问/修改属性时,它们允许进行一些计算。当然,只要定义了get/set之一,另一个是可选的。

不带属性的示例:

private int test;

public int getTest() {
    // some computation on test here, maybe?
    return test;
}

private void setTest(int test) {
    // some error/range checking, maybe?
    this.test = test;
}

带属性:

private int test;
public int Test {
    get {
        // some computation on test here, maybe?
        return test;
    }
    private set {
        // some error/range checking, maybe?
        test = value;   // value is a keyword here
    }
}

Get and set are used in properties. They can each be public, protected, or private. Similar to accessor and mutator methods, they allow some computation when code tries to access/mutate the property. Of course, as long as you define one of get/set, the other is optional.

Example without properties:

private int test;

public int getTest() {
    // some computation on test here, maybe?
    return test;
}

private void setTest(int test) {
    // some error/range checking, maybe?
    this.test = test;
}

With properties:

private int test;
public int Test {
    get {
        // some computation on test here, maybe?
        return test;
    }
    private set {
        // some error/range checking, maybe?
        test = value;   // value is a keyword here
    }
}
坦然微笑 2024-11-24 22:14:08

get{} 和 set{} 是访问器,可以轻松读取和写入私有字段。使用一个简单的示例:

public class Foo()
{ 
    //Field
    private int _bar;

    //Property
    public int Bar
    {
        get { return _bar; }
        set { _bar = value; }  
        //value is an implicit parameter to the set acccessor.
        //When you perform an assignment to the property, the value you
        //assign is the value in "value"
    }
}

在本例中,Bar 是一个公共属性,具有一个 getter 和一个 setter,允许访问私有字段 _bar,否则将无法访问该字段福类。

现在,在具有 Foo 实例的类中,您可以执行以下操作:

public class IHasAFoo()
{
    private Foo _myFoo = new Foo();

    public void SomeMethod()
    {
        _myFoo.Bar = 42;
    }
}

因此,公共访问器允许您将私有字段的值设置回 Foo 中。

希望有帮助!

get{} and set{} are accessors that offer up the ability to easily read and write to private fields. Working with a simple example:

public class Foo()
{ 
    //Field
    private int _bar;

    //Property
    public int Bar
    {
        get { return _bar; }
        set { _bar = value; }  
        //value is an implicit parameter to the set acccessor.
        //When you perform an assignment to the property, the value you
        //assign is the value in "value"
    }
}

In this case, Bar is a public property that has a getter and a setter that allows access to the private field _bar that would otherwise be inaccessible beyond class Foo.

Now in a class that has an instace of Foo, you can do this:

public class IHasAFoo()
{
    private Foo _myFoo = new Foo();

    public void SomeMethod()
    {
        _myFoo.Bar = 42;
    }
}

So the public accessor allows you to set the value of the private field back in Foo.

Hope that helps!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文