财产和公共领域有什么区别 [英] What is the difference between property and public field

查看:47
本文介绍了财产和公共领域有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已阅读有关属性的 msdn 文章.他们展示了财产的例子:

I have read msdn article about properties. They show that example of property:

// Declare a Name property of type string:
    public string Name
    {
        get 
        {
           return myName; 
        }
        set 
        {
           myName = value; 
        }
    }

然后他们说:

一旦属性被声明,它们就可以像它们一样被使用类的字段.

Once the properties are declared, they can be used as if they were fields of the class.

如果他们离开会有什么不同:

What would be the difference if they just left:

public string Name;

如果我有一个字段:private string name 并且只想拥有 getter?我应该申报吗

If I had a field: private string name and wanted to have only getter? Should I declare

public string GetName(){return name;} 还是应该以某种方式使用这些属性?

public string GetName(){return name;} or should use those properties somehow?

谁能告诉我这个例子有什么问题:

Could somebody tell me what is wrong with that example:

 private int age;
 public void setAge(int age){
   if(age < 100) 
   this.age = age;
}

推荐答案

This from Clr Via C#

This from Clr Via C#

Field 作为对象状态一部分的数据变量.字段由其名称和类型标识.

Field A data variable that is part of the object’s state. Fields are identified by their name and type.

属性 对于调用者来说,这个成员就像一个字段.但是对于类型实现者来说,它看起来像是一种(或两种)方法.属性允许实现者仅在必要时在访问值和/或计算值之前验证输入参数和对象状态.它们还允许该类型的用户具有简化的语法.最后,属性允许您创建只读或只写的字段".

Property To the caller, this member looks like a field. But to the type implementer, it looks like a method (or two). Properties allow an implementer to validate input parameters and object state before accessing the value and/or calculating a value only when necessary. They also allow a user of the type to have simplified syntax. Finally, properties allow you to create read-only or write-only "fields."

这篇关于财产和公共领域有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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