Rya*_*all 10 c# coding-style properties
我有一些自动实例化代码,我想在一个相当大的类中应用于大约15个属性.代码类似于以下内容,但每个实例的类型不同:
protected ComplexType _propertyName;
public ComplexType PropertyName
{
get
{
if (_propertyName == null) {
_propertyName = new ComplexType();
}
return _propertyName;
}
}
Run Code Online (Sandbox Code Playgroud)
要在C++中重复这个(因为有大约15个实例),我会使用预处理器宏,但我注意到C#不支持它们.
我想知道是否有人建议如何在C#中干净利落地做到这一点?
Cha*_*lie 22
这可能会使事情变得更整洁,您可以添加此方法来引入一些重用:
protected ComplexType _propertyName;
public ComplexType PropertyName
{
get
{
return GetProperty(ref _propertyName);
}
}
.
.
private T GetProperty<T>(ref T property) where T : new()
{
if (property == null)
property = new T();
return property;
}
Run Code Online (Sandbox Code Playgroud)
Mar*_*age 16
您可以使用??运算符将代码简化为一行:
protected ComplexType _propertyName;
public ComplexType PropertyName
{
get
{
return _propertyName ?? (_propertyName = new ComplexType());
}
}
Run Code Online (Sandbox Code Playgroud)
作为旁注,我可能会避免受保护的字段.如果您需要从派生类设置属性,我宁愿创建一个受保护的setter.
Guf*_*ffa 11
您可以创建一个处理延迟创建的通用结构:
public struct LazyCreate<T> where T : class, new() {
private T _value;
public T Value {
get {
if (_value == null) {
_value = new T();
}
return _value;
}
}
}
protected LazyCreate<ComplexType> _propertyName;
public ComplexType PropertyName {
get {
return _propertyName.Value;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1800 次 |
| 最近记录: |