首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >是否可以仅在属性的getter或setter上使用过时属性

是否可以仅在属性的getter或setter上使用过时属性
EN

Stack Overflow用户
提问于 2010-11-06 01:14:42
回答 2查看 4.4K关注 0票数 26

是否可以仅在属性的getter或setter上使用过时属性?

我希望能够做这样的事情:

代码语言:javascript
复制
public int Id {
    get { return _id;}
    [Obsolete("Going forward, this property is readonly",true)]
    set { _id = value;}
}

但很明显,这不会构建。有没有办法让我只把这个属性应用到setter上?

EN

回答 2

Stack Overflow用户

发布于 2010-11-06 02:44:29

我认为这是不可能的,因为出于某种原因,它已经被明确禁止用于过时属性。根据围绕属性目标定义的规则,似乎没有任何理由使过时的属性在属性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访问器,而不能应用过时属性。

代码语言:javascript
复制
[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; }
    }
}

如果您尝试创建在属性集访问器上无效的自己的属性,并将其应用于属性集访问器,则可能会注意到错误消息略有不同。自定义属性的错误消息将是“属性'YourCustomAttribute‘在此声明类型上无效。”,而过时属性的错误消息是“属性’过时‘在属性或事件访问器上无效”。错误消息不同的事实使我相信,无论出于何种原因,这是一条显式地内置于编译器中的过时属性的规则,而不是依赖于AttributeUsage属性,后者理应应用于过时属性。

票数 15
EN

Stack Overflow用户

发布于 2019-04-04 13:15:04

此功能现已包含在C# 8.0中。

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

进行这些更改的PR在这里:https://github.com/dotnet/roslyn/pull/32571

票数 14
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4108300

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档