C# - 自动属性 ​​VS 3.0 之前的属性 [英] C# - auto-properties VS pre-3.0 properties

查看:33
本文介绍了C# - 自动属性 ​​VS 3.0 之前的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对不起,如果我的问题与代码风格有关,但对于简单的情况,下面哪个更好?

案例 1:

private static int number = 1;public static int 数字{得到{返回号码;}设置 { 数字 = 值;}}

情况 2:

public static int Number{得到;放;}

我认为案例 2 更好,因为当您的类中有很多属性时,它们不会占用太多空间并且文件大小会减少.

解决方案

下面的语法称为

Excuse me if my question is pretty much about code-style, but for simple cases which of the bellow is better?

CASE 1:

private static int number = 1;
public static int Number
{
    get { return number; }
    set { number = value; }
}

CASE 2:

public static int Number
{
    get;
    set;
}

I think case 2 is better because, when you have many properties in your class they won't consume so much space and the filesize will be reduced.

解决方案

The syntax below is called auto properties, it doesn't matter in the terms of file size since in compilation time, a field is generated anyway (see, decompilation in the end of the answer) and there are get and set methods in the compilation results in both cases.

Auto properties allow you to keep your code more organized and short which is good for your code maintainability and readability, therefore you should prefer them when possible.

We will put aside the "In field without auto-property you can assign default value" topic for a second (also, it is possible now in auto-properties too in c# 6.0), sometimes, you want to run some more code inside the get or set methods of the property, like invoking event handles or validating the values, that's where standard property declaration comes into the picture, for example:

private int mNumber;

public int Number
{
    get
    {
        return Number;
    }
    set
    {
        if (Number == 8)
        {
            throw new CannotReceive8Exception();
        }
        else
        {
            mNumber = value;
        }
    }
}

If you look at the decompiled code of this code:

public int Number { get; set; }

You will see that the compiler has added a background private field anyway:

这篇关于C# - 自动属性 ​​VS 3.0 之前的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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