C#等效于C++宏并使用自动<>属性

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.

  • @Kelix:但你实际上是通过保护字段来放弃成员保护.现在,任何派生类都可以完全访问您的字段.这有点类似于拥有公共字段,除了只有派生类而不是所有类都可以访问这些字段. (2认同)
  • @Kelix - 你倒退了.你应该想"我不喜欢在没有必要的地方允许访问". (2认同)

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)


Tho*_*que 6

即使它没有直接解决您的问题,您也可以查看Lazy<T>.NET 4.0附带的新类.它专为延迟初始化方案而设计.