访问自动属性 ​​- C# [英] Access automatic property - c#

查看:92
本文介绍了访问自动属性 ​​- C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

自动性能添加到语言中有关.NET 3,营造出私人领域,反正使用的代码:

 公共字符串foo的{获取;集;} 

是否有可能真正得到任何形式的参考这个私人领域?



我想要做这样的事情。

 公共字符串富{获得{/ *一些代码来检查foo的空值等* /};集;} 

不失这种自动功能属性和写作类似

 私人字符串_foo = NULL; 
公共字符串foo的{获得{_foo == NULL _foo =你好?;返回_foo;}集合{_foo =值;}}


解决方案

自动属性的支持字段是匿名的;你不能从它的getter或setter内访问它。



如果您需要实现您的getter或setter自己的逻辑,你的财产不被视为自动再。反正



自动属性来这里只是为了节省打字看到的枯燥和顺眼,这些众人:

 私有对象_x; 

公开对象X
{
{返回_x; }
集合{_x =价值; }
}


Automatic properties were added to the language in about .net 3 which create a 'private' field, anyway, using the code:

public string foo {get;set;}

Is it possible to actually get any sort of reference to this private field?

I want to do something like

public string foo {get{/*some code to check foo for nulls etc*/};set;}

Without losing this automatic property feature and writing something like

private string _foo = null;
public string foo{get{_foo==null?_foo="hello"; return _foo;}set{_foo=value;}}

解决方案

The backing field of an automatic property is anonymous; you can't access it from within its getter or setter.

If you need to implement your own logic in your getter or setter, your property isn't considered automatic anymore anyway.

Auto properties are simply there to save the tedium of typing, and eyesore of seeing, multitudes of these:

private object _x;

public object X
{
    get { return _x; }
    set { _x = value; }
}

这篇关于访问自动属性 ​​- C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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