如何使用获取集访问说明符 [英] how to use get set access specifiers

查看:61
本文介绍了如何使用获取集访问说明符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在c ++中声明变量,只需这样写,int x = 10;
我最近开始使用c#.i,我们在变量声明中发现我们正在使用get set
,这有什么用,我们不能像c ++那样直接声明变量.
谁能给我清楚的例子.
感谢

in c++ to declare variable,just write like this,int x=10;
i recently moced to c#.i found in variables declaration we are using get set
,what is the use of this,cant we declare variables directly like c++.
can any one give me clear example of this.
thanks

推荐答案

我认为访问说明符和访问器是不同的东西吗?
好看看:
http://msdn.microsoft.com/en-us/library/aa287786%28v = vs.71%29.aspx [ ^ ]

http://msdn.microsoft.com/en-us/library/w86s7x04.aspx [ ^ ]也
有关更多信息
i think access specifiers and accessors are different things know?
well have a look at :
http://msdn.microsoft.com/en-us/library/aa287786%28v=vs.71%29.aspx[^]

and http://msdn.microsoft.com/en-us/library/w86s7x04.aspx[^] also
for more information


我们可以用相同的方式声明变量:
We can declare variables in the same way:
int myInt = 6;
string myString = "hello";

这些被称为fields

当使用get和set访问器时,您将其声明为property,这是一个非常不同的动物.属性是访问变量时调用的一组方法-获取值时调用get方法,而分配值时调用set方法.

这更加灵活:您不仅可以拥有一个公共获取器,以便任何人都可以获取该值,还可以添加一个私有(或受保护的或内部的)setter来防止类外的更改.
您还可以在get和set方法中执行任何操作-您可以从多种来源构建字符串变量:

These are called fields

When you use the get and set accessors, you are declaring it as a property which is a very different animal. A property is a a set of methods that are called when a variable is accessed - the get method is called when you fetch the value and the set method is called when you assign a value.

This is a lot more flexible: not only can you have a public getter so anyone can get the the value, you can add a private (or protected, or internal) setter to prevent changes outside your class.
You can also do anything within the get and set methods - you can build your string variable from a number of sources:

private string firstName;
private string secondName;
public string Name
   {
   get { return firstName + " " + secondName; }
   set 
      {
      string[] parts = value.Split(' ');
      firstName = parts[0];
      secondName = parts[1];
      }
   }
public string Email
   {
   get { return firstName + "." + secondName + "@myCompany.com";
   }

这有助于使类的内部内容与正在使用它们的类保持距离.


[edit]糟糕!忘了声明字符串数组...:O-OriginalGriff [/edit]

This helps to keep the internals of your class away from the class that is using them.


[edit]Oops! Forgot to declare string array... :O - OriginalGriff[/edit]


这篇关于如何使用获取集访问说明符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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