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

是否可以仅对属性的getter或setter使用过时属性

c#
  •  22
  • wusher  · 技术社区  · 15 年前

    是否可以只对属性的getter或setter使用过时属性?

    public int Id {
        get { return _id;}
        [Obsolete("Going forward, this property is readonly",true)]
        set { _id = value;}
    }
    

    但很明显,这不会建立。是否有一个解决方法允许我将这个属性应用于setter?

    2 回复  |  直到 15 年前
        1
  •  15
  •   Dr. Wily's Apprentice    15 年前

    我认为这是不可能的,因为,出于某种原因,它被明确禁止用于过时属性。根据围绕属性目标定义的规则,似乎没有任何理由认为过时的属性在属性get或set访问器上无效。为了将属性应用于属性集访问器, that attribute must be applicable to either a method, parameter, or return value target . 如果你看 the Obsolete attribute ,可以看到“method”是该属性的有效目标之一。

    实际上,您可以使用与过时属性相同的有效目标来定义自己的属性 with the AttributeUsage attribute ,您会发现可以将其应用于属性get或set访问器,而不能应用过时的属性。

    [AttributeUsage(AttributeTargets.Method)]
    class MyMethodAttribute : Attribute { }
    
    class MyClass
    {
        private int _Id;
    
        public int Id
        {
            get { return _Id; }
    
            [MyMethodAttribute] // this works because "Method" is a valid target for this attribute
            [Obsolete] // this does not work, even though "Method" is a valid target for the Obsolete attribute
            set { _Id = value; }
        }
    }
    

        2
  •  12
  •   Yair Halberstadt    6 年前

    这种能力现在已经包含在C#8.0中。

    感谢Wily博士的徒弟,他指出这与他回答中的其他属性不一致,并激励我实现这一点。

    https://github.com/dotnet/roslyn/pull/32571