如何在ASP.NET C#中使用get和set? [英] How to use get and set in ASP.NET C# ?
问题描述
嘿伙计们,
我在这里得到了这个代码:
private string _firstName;
public string FirstName
{
get { return _firstName; }
set {_ firstName = value ; }
}
但我不知道它是如何工作的我试图玩它。我假设这意味着如果我在名为_firstName的私有对象中放置一个值,我可以在公共对象FirstName中使用它,即使它是私有的。
任何人?
私有字符串是在代码中执行FirstName =....时设置的后备字段。实际上发生的是这段代码转换为隐藏的集合调用(这是编译器在表面下所做的)。伪逻辑如下所示:public void FirstName_Set( string value )
{
_firstName = 值跨度>;
}通过这样做,我们确保从外部类隐藏_firstName(我们封装它)。当然,如果你所做的只是设置一个简单的值,而你没有做任何类似序列化或更复杂的验证形式,那么你可能只需要
public string FirstName;
请阅读这些..
c#中的封装 [< a href =http://msdn.microsoft.com/en-us/library/dd460654.aspxtarget =_ blanktitle =New Window> ^ ]
封装oops [ ^ ]
http://www.dotnetperls.com/encapsulate-field [ ^ ]
Hey guys,
I got this code here:
private string _firstName;
public string FirstName
{
get { return _firstName; }
set { _firstName = value; }
}
But i don't get how it work I tried to play around with it. I'm assuming that it means if I put a value in the private object named _firstName I can use it inside the public object FirstName even if it's private.
Anyone?
The private string is a backing field that is set when you do FirstName = "...." in your code. Effectively what happens is that this code translates into a hidden set call (that's what the compiler does under the surface). The pseudo-logic looks like this:public void FirstName_Set(string value) { _firstName = value; }By doing this, we ensure that _firstName is hidden from outside classes (we encapsulate it). Of course, if all you are doing is setting a simple value and you aren't doing anything like serialization or more complex forms of validation, then you might as well just have
public string FirstName;
Please read these..
Encapsulation in c#[^]
Encapsulation oops[^]
http://www.dotnetperls.com/encapsulate-field[^]
这篇关于如何在ASP.NET C#中使用get和set?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!