C#-使用属性v.字段的优势 [英] C# - Advantages for using properties v. fields

查看:58
本文介绍了C#-使用属性v.字段的优势的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
字段与字段之间有什么区别是C#中的属性?
C#.NET 3.5中的属性与字段之间的差异+

前一段时间,我继承了一个C#Web应用程序,其中大多数可能是字段的类成员都通过以下两种方式之一定义为属性:

Some time ago I inherited a C# web app wherein most class members that could be fields are defined as properties in one of the following two manners:

private Guid id;
public Guid Id
{
  get { return id; }
  set { id = value; }
}

public int someValue{ get; set; }

即,获取者/设置者除了将值传递到私有字段或从私有字段传递值外,不做任何其他事情.在这些情况下,将这些成员构建为属性还是字段是否有优势(或理由)?反之亦然?

Namely, the getters/setters don't do anything other than ferry a value to/from a private field. In these cases, is there an advantage [or justification] for building these members out as properties vs. fields? And vice versa?

我将其更改为字段会违反任何潜规则或最佳做法吗?是否存在明显的性能差异-例如,以一种方式或另一种方式为N个对象的列表增加 someValue ?(我目前的理解是,现场访问必定不太复杂[和高效].)

Would I be violating any unspoken rules or best practices by changing them to fields? Is there a notable performance difference -- for instance, incrementing someValue for a list of N objects one way or the other? (My current understanding is that field access is necessarily less complex [and efficient].)

推荐答案

主要是一种OOP(面向对象编程)概念:封装您可以在此处查看简要说明;

It's mainly an OOP (Object Oriented Programming) notions: Encapsulation You can view a brief description here;

关于封装的WikiPedia条目

例如,可能的用途之一是在尝试分配值时,调用一个函数来验证此新值.例如:

One of the possible uses is for example when trying to assign a value, to call a function to validate this new value. For example:

private Guid id;
public Guid Id
{
    get { return id; }
    set
    { 
        if (checkValue(value)==true)
        {
            id = value;
        } 
    }
}

这篇关于C#-使用属性v.字段的优势的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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