简体   繁体   English

如何在C#中调用getter或setter

[英]How do I call a getter or setter in C#

I understand how to create a getters and setters 我理解如何创建一个getter和setter

public myClass
{
    public int myVal { get; set; }

    // more stuff
}

but I don't understand how to call it later on. 但我不明白以后如何调用它。

public myOtherClass
{
    public myOtherClass()
    {
         myClass localMyClass = new myClass();

         localMyClass.???set??? = 42;  
         // Intelisense doesn't seem to give any obvious options after I enter 
         // the period.
    }
}

How should I set the value of myVal in localMyClass? 我应该如何在localMyClass中设置myVal的值?

localMyClass.myVal = 42;

Getters and setters let you treat the values like public properties. 使用getter和setter可以将值视为公共属性。 The difference is, you can do whatever you want inside the functions that do the getting and setting. 不同的是,您可以在获取和设置的功能中执行任何操作。

Examples: 例子:

store other variables 存储其他变量

private int _myVal, myOtherVal;
public int MyVal { get; set { _myVal = value; myOtherVal++; } }

make numbers up / return constants 使数字增加/返回常数

public int MyVal { get { return 99; } set; }

throw away the setter 扔掉二传手

private int _myVal;
public int MyVal { get { return _myVal; } set { ; } }

In each of these cases, the user will feel like it's just a public data member, and simply type 在每种情况下,用户都会觉得它只是一个公共数据成员,只需键入即可

localMyClass.myVal = 42;
int i = localMyClass.myVal;

The gettors and settors let you make an implementation of your own. gettors和settors让你实现自己的实现。 Also, as Hogan says, "There are a number of libraries and add-ons [eg MVC.NET] that require you to use getter and setter functions" - even if it's for the trivial {get; set;} 另外,正如Hogan所说,“有许多库和附加组件[例如MVC.NET]需要你使用getter和setter函数” - 即使它是为了琐碎的{get; set;} {get; set;} case. {get; set;} case。

Set: 组:

localMyClass.myVal = 42

Get: 得到:

int variable = localMyClass.myVal;

From the outside, the syntax for accessing getters and setters is indistinguishable from that of accessing variables. 从外部来看,访问getter和setter的语法与访问变量的语法无法区分。 Assignments translate into calls of setters, while plain expression uses translate into calls of getters. 赋值转换为setter的调用,而plain表达式使用translate转换为getter的调用。

In intellisense, the list of getters and setters should open upon placing a dot . 在intellisense中,getter和setter列表应该在放置一个点时打开. after the variable name. 变量名后面。 Properties should have blue markers to the left of them (as opposed to magenta-colored markers to the left of methods). 属性应在其左侧具有蓝色标记(与方法左侧的品红色标记相对)。

You want this 你要这个

localMyClass.myVal = 42;  

to call the setter 打电话给二传手

and this 和这个

varName = localMyClass.myVal;

to call the getter. 打电话给吸气鬼。

Get: var tmp = localMyClass.myVal; 获取: var tmp = localMyClass.myVal;

Set: localMyClass.myVal = 2; 设置: localMyClass.myVal = 2;

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

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