制作这样的属性的目的是什么? [英] What is the purpose of making properties like this?

查看:112
本文介绍了制作这样的属性的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么有人要使用:

 公共 字符串测试{得到; 设置; } 



相对于:

 私有 字符串测试;
公共 字符串测试{
    获取 {返回测试;}
    设置 {test = ;}
} 



只是好奇.

解决方案

您不需要声明变量,也不会犯错误并使用错误的变量.

如果内存适合我,则您无法在早期版本(C#1.1)中执行此操作.我可能会误会,因为我在有清理的那一刻逃离了那个框架.

无论如何,我会做第一个,因为正如OriginalGriff所说的那样,没有错.但是另一方面,如果需要触发任何事件或其他某些事情(例如INotifyPropertyChanged),我将执行第二步.但是再说一遍,您的示例中没有任何内容.

哦,不要忘记更少的代码行.除非您通过代码行获得报酬(如果可以,请联系我,以便我可以将您的履历表转发给我..我有一个很好的迷恋系统:D),当您查看较大的对象时,这样做有很大的优势/system.


它可能对您有帮助,

自动实现的属性(C#编程指南) [public string test{ get; set; }



as opposed to:

private string test;
public string Test{ 
    get{ return test;} 
    set{ test = value;} 
}



Just Curious.

解决方案

You don''t need to declare the variable, and you can''t make a mistake and use the wrong one.
That''s about it, really.


The earlier actually makes more sence to me unless you plan on putting logic in the setter or getter.

If memory serves me right you could not do that in the earlier versions (C# 1.1). I could be mistaken though as I fled out of that framework the moment there was a clearing.

Anyways, I would do the first because as OriginalGriff said there is no mistaken. But on the other hand I would do the second if any events needed to be fired or something (e.g. INotifyPropertyChanged). But then again, your example does not have anything of the sort in it.

Oh and dont''t forget less lines of code. Unless you are getting paid by lines of code (which if you are please contact me so I can forward you my resume.. I got a great system for obsufication :D), there is a serious advantage to this when looking at a larger object/system.


It might help you,

Auto-Implemented Properties (C# Programming Guide)[^]

:)


这篇关于制作这样的属性的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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