本文介绍了属性和方法之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,在返回值时,哪个比较好用

Which one is better to use when it come to return value for example

public int EmployeeAge
{
    get{return intEmployeeAge};
}

还有

public int EmployeeAge()
{
    return intEmployeeAge;
}

哪个更好?为什么?当我们遇到上述安全条件时,最佳的编程实践是什么?

Which one is better and why? And what is best programming practice to use when we have secnario like above ?

推荐答案

属性是表达对象功能的一种有用方法,它允许以通用方式进行get/set设置,而API可以使用这种方式,例如数据绑定,反射和序列化.因此,对于对象的简单 values 来说,属性很方便.属性不能接受参数,不应有明显的副作用*,并且应快速且可重复地返回.而且,没有扩展属性"(以反映扩展方法)或泛型属性之类的东西.

Properties are a useful way of expressing a feature of an object, allowing get/set in a common way that can be used by APIs like data-binding, reflection and serialization. So for simple values of the object, properties are handy. Properties can't take arguments, should not have significant side-effects*, and should return quickly and repeatably. Also, there is no such thing as an "extension property" (to mirror an extension method) nor a generic property.

(**延迟加载等并不少见)

(*=lazy loading etc isn't uncommon, however)

方法(C#没有函数)更适合表示状态发生变化或期望花费一些时间且不一定可重现的事物.它们不倾向于在绑定/序列化等工作.

Methods (C# doesn't have functions) are better for expressing things that either change the state, or which have an expectation of taking some time and not necessarily being reproducible. They don't tend to work in binding / serialization etc.

请注意,属性实际上只是一种编写方法的特殊方式. 功能几乎没有什么区别.一切都与表达意图有关.但是,您不想要公开的一件事是 fields (实际的intEmployeeAge实例变量).

Note that properties are actually just a special way of writing methods. There is little functional difference. It is all about expressing intent. The one thing you don't want to expose, however, is fields (the actual intEmployeeAge instance variable).

所以我会:

public int EmployeeAge { get{return intEmployeeAge}; }

或仅(如果在Employee对象上):

or just (if on the Employee object):

public int Age { get{return intEmployeeAge}; }

当然...然后问题变成以什么为单位?"我以为是几年?

Of course... then the question becomes "in what unit?" I assume that is years?

这篇关于属性和方法之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 17:59