C#等效于C ++宏和使用自动<>属性 [英] C# Equivalent for C++ Macros and using Auto<> Properties

查看:156
本文介绍了C#等效于C ++宏和使用自动<>属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些自动实例代码,我想申请到大约15属性在一个相当大的类。该代码是类似于以下,但在类型是不同的为每个实例:

I have some auto-instantiation code which I would like to apply to about 15 properties in a fairly big class. The code is similar to the following but the type is different for each instance:

protected ComplexType _propertyName;
public ComplexType PropertyName
{
    get
    {
        if (_propertyName == null)
            _propertyName = new ComplexType();

        return _propertyName;
    }
}



在C重复这一++(因为有〜15实例),我会使用的预处理宏的,但我发现C#不支持他们。

To repeat this in C++ (as there are ~15 instances), I would have used a preprocessor macro but I notice C# doesn't support them.

我想知道如果任何人有一个建议,如何做到这一点干净的C#?

I am wondering if anyone has a recommendation on how to do this cleanly in C#?

推荐答案

这可能使事情更简洁,可以添加这个方法来介绍一些重用:

This might make things a bit neater, you could add this method to introduce some reuse:

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;
}

这篇关于C#等效于C ++宏和使用自动&LT;&GT;属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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