给 C# 自动属性一个初始值的最佳方法是什么? [英] What is the best way to give a C# auto-property an initial value?

查看:32
本文介绍了给 C# 自动属性一个初始值的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何给 C# 自动属性一个初始值?

How do you give a C# auto-property an initial value?

我要么使用构造函数,要么恢复到旧语法.

I either use the constructor, or revert to the old syntax.

使用构造函数:

class Person 
{
    public Person()
    {
        Name = "Initial Name";
    }
    public string Name { get; set; }
}

使用普通属性语法(带有初始值)

private string name = "Initial Name";
public string Name 
{
    get 
    {
        return name;
    }
    set
    {
        name = value;
    }
}

有更好的方法吗?

推荐答案

在 C# 5 及更早版本中,要为自动实现的属性提供初始值,您必须在构造函数中进行.

In C# 5 and earlier, to give auto implemented properties an initial value, you have to do it in a constructor.

从 C# 6.0 开始,您可以内联指定初始值.语法是:

Since C# 6.0, you can specify initial value in-line. The syntax is:

public int X { get; set; } = x; // C# 6 or higher

DefaultValueAttribute 旨在供 VS 设计者(或任何其他使用者)用于指定默认值,而不是初始值.(即使在设计对象中,初始值也是默认值).

DefaultValueAttribute is intended to be used by the VS designer (or any other consumer) to specify a default value, not an initial value. (Even if in designed object, initial value is the default value).

在编译时 DefaultValueAttribute 不会影响生成的 IL 并且不会被读取以将属性初始化为该值(请参阅 DefaultValue 属性不适用于我的自动属性).

At compile time DefaultValueAttribute will not impact the generated IL and it will not be read to initialize the property to that value (see DefaultValue attribute is not working with my Auto Property).

影响 IL 的属性示例是 ThreadStaticAttributeCallerMemberNameAttribute, ...

Example of attributes that impact the IL are ThreadStaticAttribute, CallerMemberNameAttribute, ...

这篇关于给 C# 自动属性一个初始值的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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