加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C#等效于C宏并使用Auto <>属性

发布时间:2020-12-15 06:55:05 所属栏目:百科 来源:网络整理
导读:我有一些自动实例化代码,我想在一个相当大的类中应用于大约15个属性.代码类似于以下内容,但每个实例的类型不同: protected ComplexType _propertyName;public ComplexType PropertyName{ get { if (_propertyName == null) _propertyName = new ComplexType
我有一些自动实例化代码,我想在一个相当大的类中应用于大约15个属性.代码类似于以下内容,但每个实例的类型不同:
protected ComplexType _propertyName;
public ComplexType PropertyName
{
    get
    {
        if (_propertyName == null)
            _propertyName = new ComplexType();

        return _propertyName;
    }
}

要在C中重复(因为有?15个实例),我将使用一个预处理宏,但我注意到C#不支持它们.

我想知道有没有人有建议如何干净地在C#中做这个?

解决方法

这可能会使事情有点整洁,可以添加这种方法来引入一些重用:
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;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读