代码之家  ›  专栏  ›  技术社区  ›  Stephan

是否可以扩展属性?

c#
  •  0
  • Stephan  · 技术社区  · 6 年前

    在应用程序中,我使用不同的框架/技术来序列化/反序列化对象。要忽略对象中的属性,有如下属性 BsonIgnore JsonIgnore .

    [JsonIgnore]
    [BsonIgnore]
    public bool MyProperty
    {
        get;
        set; 
    }
    

    如何创建从 布索尼奥雷 杰索尼诺 所以我只需要为 MyProperty ?

    以下不起作用,因为属性必须扩展 System.Attribute .

    [AttributeUsage(AttributeTargets.Class)]
    public class MyIgnoreAttribute : BsonIgnore, JsonIgnore
    { ... }
    
    -------------------------
    
    [MyIgnore]
    public bool MyProperty
    {
        get;
        set; 
    }
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   Richardissimo    6 年前

    C#不支持多重继承,而且每种类型都是 sealed ,所以他们无论如何也不能继承。但可能有不同的方法来做你想做的事。

    如果它是一个可预测的事物,例如:如果有一个属性的事物总是有另一个属性;您可以使用面向方面编程在编译时注入另一个属性。

    你的下一个问题是 ,答案将取决于你使用什么产品。

    之后的问题是 ,这是离题的,如图所示 here

        2
  •  2
  •   Backs    6 年前

    这是无用的,不可能的。

    JsonIgnoreAttribute :

    namespace Newtonsoft.Json
    {
      /// <summary>
      /// Instructs the <see cref="T:Newtonsoft.Json.JsonSerializer" /> not to serialize the public field or public read/write property value.
      /// </summary>
      [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
      public sealed class JsonIgnoreAttribute : Attribute
      {
      }
    }
    

    如你所见,它什么也不做。

    在newtonsoft框架中 there is a code JsonIgnoreAttribute公司

    也, JsonIgnoreAttribute公司 是密封的,你不能扩展它。