问题描述
我习惯于这样写类:
public class foo {
private string mBar = "bar";
public string Bar {
get { return mBar; }
set { mBar = value; }
}
//... other methods, no constructor ...
}
将 Bar 转换为 auto-property 似乎方便简洁,但是如何在不添加构造函数并将初始化放入其中的情况下保留初始化?
Converting Bar to an auto-property seems convenient and concise, but how can I retain the initialization without adding a constructor and putting the initialization in there?
public class foo2theRevengeOfFoo {
//private string mBar = "bar";
public string Bar { get; set; }
//... other methods, no constructor ...
//behavior has changed.
}
您可以看到,添加构造函数与我应该从自动属性中获得的工作量节省不一致.
You could see that adding a constructor isn't inline with the effort savings I'm supposed to be getting from auto-properties.
这样的事情对我来说更有意义:
Something like this would make more sense to me:
public string Bar { get; set; } = "bar";
推荐答案
更新 - 下面的答案是在 C# 6 出现之前编写的.在 C# 6 中,您可以编写:
Update - the answer below was written before C# 6 came along. In C# 6 you can write:
public class Foo
{
public string Bar { get; set; } = "bar";
}
你可以也编写只读的自动实现的属性,这些属性只能在构造函数中写入(但也可以给定一个默认初始值):
You can also write read-only automatically-implemented properties, which are only writable in the constructor (but can also be given a default initial value):
public class Foo
{
public string Bar { get; }
public Foo(string bar)
{
Bar = bar;
}
}
很遗憾,目前无法做到这一点.您必须在构造函数中设置值.(使用构造函数链可以帮助避免重复.)
It's unfortunate that there's no way of doing this right now. You have to set the value in the constructor. (Using constructor chaining can help to avoid duplication.)
自动实现的属性现在很方便,但肯定会更好.我发现自己并不希望像只读自动实现的属性那样频繁地进行这种初始化,该属性只能在构造函数中设置并由只读字段支持.
Automatically implemented properties are handy right now, but could certainly be nicer. I don't find myself wanting this sort of initialization as often as a read-only automatically implemented property which could only be set in the constructor and would be backed by a read-only field.
这在 C# 5 之前(包括 C# 5)并没有发生,但正计划在 C# 6 中进行 - 无论是在允许在声明点初始化,和都允许只读自动实现要在构造函数主体中初始化的属性.
This hasn't happened up until and including C# 5, but is being planned for C# 6 - both in terms of allowing initialization at the point of declaration, and allowing for read-only automatically implemented properties to be initialized in a constructor body.
这篇关于初始化 C# 自动属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!