定义类的属性 [英] Defining properties of a class

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

问题描述

谁能告诉我

public class Vendor
{
    public string VendorName { get; set; }
}

public class Vendor
{
    private string vendorName = string.Empty; 

    public string VendorName
    {
        get { return vendorName; }
        set { vendorName = value; }
    }
}

使用私有变量有什么好处吗?这样做只是浪费时间和线路?没有对类中的属性进行任何操作.

Is there any benefit of using a private variable? Doing so is only wastage of time and lines? There are no manipulations done to the property within the class.

谢谢

推荐答案

C# 3 引入了自动实现的属性,这使您的第一个代码片段成为可能.编译器将为您创建支持字段,这将使编译后的代码等同于第二个代码段的编译后的代码.如果您使用的是 <= 2.0 代码库,您将使用第二个代码段.

C# 3 introduced auto-implemented properties, which makes your first snippet possible. The compiler is going to create your backing field for you, which would make the compiled code equivalent to the compiled code of your second snippet. If you're working in a <= 2.0 code base, you'll be using the second snippet.

使用私有变量的好处是如果您在设置属性时执行某种验证,例如将整数限制为正值或拒绝空字符串.如果您不需要这样的行为,或者只是希望在其他地方处理这些活动并且该属性只是一个获取和设置,那么请使用自动实现的版本.

The benefit of using a private variable would be if you performed some sort of validation when the property is set, such as restricting integers to positive values or rejecting null strings. If you do not need such behavior or simply wish to handle those activities elsewhere and the property is just a fetch and set, then use the auto-implemented version.

这篇关于定义类的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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