【问题标题】:Is it possible to change structure of class via attributes?是否可以通过属性更改类的结构?
【发布时间】:2019-06-12 00:41:23
【问题描述】:

现在我正在阅读“CLR via C#”一书,我对以下问题感兴趣 - 是否可以通过如下属性更改类的结构:

[UseFooAttr(true)]
class A
{
  if (IsDefined(typeof(UseFooAttr)))
    public Foo FooProperty{get; set}
};

但我不确定这种方法是否有一些真正的好处。

【问题讨论】:

    标签: c# reflection


    【解决方案1】:

    不,那是不可能的。但你可能想使用conditional compilation:

    #define UseFooPropertery // define pre-processor symbol
       class A
       {
    #if UseFooProperty // check if symbol is defined
           public Foo FooProperty{get; set}
    #endif
       }
    

    除了#if/#endif 预处理器指令,您还可以使用Conditional 属性:

    #define UseFooPropertery // define pre-processor symbol
       class A
       {
           [Conditional("UseFooPropertery")]
           public Foo FooProperty{get; set}
       }
    

    您可能想define the symbol in your project settings 而不是将它们放入您的代码中。

    【讨论】:

      猜你喜欢
      • 2014-08-03
      • 1970-01-01
      • 2017-10-05
      • 2013-10-12
      • 1970-01-01
      • 1970-01-01
      • 2022-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多