在C#中,是什么使字段与属性不同?何时应该使用字段而不是属性?
当前回答
IMO,财产只是我们以前使用的“SetXXX()”“GetXX()”函数/方法/接口对,但它们更简洁优雅。
其他回答
财产显示字段。字段应该(几乎总是)对类保持私有,并通过get和set财产进行访问。财产提供了一个抽象级别,允许您更改字段,同时不影响使用类的事物访问字段的外部方式。
public class MyClass
{
// this is a field. It is private to your class and stores the actual data.
private string _myField;
// this is a property. When accessed it uses the underlying field,
// but only exposes the contract, which will not be affected by the underlying field
public string MyProperty
{
get
{
return _myField;
}
set
{
_myField = value;
}
}
// This is an AutoProperty (C# 3.0 and higher) - which is a shorthand syntax
// used to generate a private field for you
public int AnotherProperty { get; set; }
}
@Kent指出,财产不需要封装字段,它们可以对其他字段进行计算,也可以用于其他目的。
@GSS指出,您还可以在访问属性时执行其他逻辑,例如验证,这是另一个有用的功能。
面向对象的编程原则表明,类的内部工作应该对外界隐藏。如果公开一个字段,本质上就是公开类的内部实现。因此,我们用财产(Properties)(或Java中的方法)包装字段,使我们能够在不破坏代码的情况下更改实现。考虑到我们可以在Property中放置逻辑,还允许我们在需要时执行验证逻辑等。C#有一个可能令人困惑的自动属性概念。这允许我们简单地定义Property,而C#编译器将为我们生成私有字段。
public class Person
{
private string _name;
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
public int Age{get;set;} //AutoProperty generates private field for us
}
(这真的应该是一条评论,但我不能发表评论,所以如果不适合作为帖子,请原谅)。
我曾经在一个地方工作,推荐的做法是使用公共字段而不是财产,而等效的属性def只访问字段,如:
get { return _afield; }
set { _afield = value; }
他们的理由是,如果需要的话,公共领域可以在未来晚些时候转化为财产。当时我觉得有点奇怪。从这些帖子来看,这里似乎也没有多少人会同意。你可能会说些什么来改变现状?
编辑:我应该补充一点,这里的所有代码库都是同时编译的,所以他们可能认为更改类的公共接口(通过将公共字段更改为属性)不是问题。
财产是一种特殊的类成员。在财产中,我们使用预定义的Set或Get方法。它们使用访问器,通过访问器我们可以读取、写入或更改私有字段的值。
例如,让我们使用一个名为Employee的类,其中包含name、age和Employee_Id的私有字段。我们无法从类外部访问这些字段,但可以通过财产访问这些私有字段。
我们为什么使用财产?
公开类字段并公开它是有风险的,因为您无法控制分配和返回的内容。
为了通过示例清楚地理解这一点,让我们以一个具有ID、密码和姓名的学生班级为例。现在在这个例子中,公共领域的一些问题
ID不应为-ve。名称不能设置为空合格标记应为只读。如果缺少学生姓名,则不应返回姓名。
为了解决这个问题,我们使用Get和set方法。
// A simple example
public class student
{
public int ID;
public int passmark;
public string name;
}
public class Program
{
public static void Main(string[] args)
{
student s1 = new student();
s1.ID = -101; // here ID can't be -ve
s1.Name = null ; // here Name can't be null
}
}
现在我们以get和set方法为例
public class student
{
private int _ID;
private int _passmark;
private string_name ;
// for id property
public void SetID(int ID)
{
if(ID<=0)
{
throw new exception("student ID should be greater then 0");
}
this._ID = ID;
}
public int getID()
{
return_ID;
}
}
public class programme
{
public static void main()
{
student s1 = new student ();
s1.SetID(101);
}
// Like this we also can use for Name property
public void SetName(string Name)
{
if(string.IsNullOrEmpty(Name))
{
throw new exeception("name can not be null");
}
this._Name = Name;
}
public string GetName()
{
if( string.IsNullOrEmpty(This.Name))
{
return "No Name";
}
else
{
return this._name;
}
}
// Like this we also can use for Passmark property
public int Getpassmark()
{
return this._passmark;
}
}
这里清楚地解释了区别。然而,只是为了总结和强调:
字段封装在类内部以进行内部操作,而财产可用于将类公开给外部世界,以及共享链接中显示的其他内部操作。此外,如果您希望基于特定字段的值加载某些方法或用户控件,则属性将为您完成此操作:
例如:
您可以在asp.net页面中的用户控件下方运行,只需为aspx页面中控件的Id前缀赋值,如下所示:
useMeId.Id=5 ---call the property of user control "UseMe.ascx"
使用Me.ascx
<%@ Register Src=~/"UseMe.ascx" TagPrefix="uc" TagName="UseMe" %>
<uc:UseMe runat="Server" id="useMeId" />
UseMe.ascx.cs
private int currentId;
public int Id
{
get
{
return currentId;
}
set
{
currentId = value;
LoadInitialData(currentId);
}
}
Private void LoadinitialData(int currentIdParam)
{
//your action
}
推荐文章
- 实体框架核心:在上一个操作完成之前,在此上下文中开始的第二个操作
- 如何为构造函数定制Visual Studio的私有字段生成快捷方式?
- 如何使用JSON确保字符串是有效的JSON。网
- AppSettings从.config文件中获取值
- 通过HttpClient向REST API发布一个空体
- 如何创建类属性?
- 如何检查IEnumerable是否为空或空?
- 自动化invokerrequired代码模式
- 在c#代码中设置WPF文本框的背景颜色
- 在c#中,什么是单子?
- c#和Java中的泛型有什么不同?和模板在c++ ?
- c#线程安全快速(est)计数器
- 如何将此foreach代码转换为Parallel.ForEach?
- 如何分裂()一个分隔字符串到一个列表<字符串>
- 如何转换列表<字符串>列表<int>?