简体   繁体   English

C#自定义过时属性

[英]C# custom obsolete attribute

I was wondering if it's possible to create a custom obsolete class. 我想知道是否可以创建一个自定义的过时类。 I need it and I hate the fact Obsolete shows up this warning before my input: SOMETHING is Obsolete:. 我需要它并且我讨厌在我输入之前Obsolete出现这个警告的事实:SOMETHING已经过时了: I just want to give a warning/error when I use the field/method with ONLY my input, so for example: 我只想在仅使用输入的字段/方法时发出警告/错误,例如:

[CustomObsolete("Hello")]
public int i = 0;

Will give warning/debug Hello. 将给出警告/调试你好。

Is this possible? 这可能吗? If I use #warning/#error, it will ALWAYS show up the error/warning. 如果我使用#warning / #error,它将始终显示错误/警告。

No, ObsoleteAttribute is effectively hard-coded into the C# compiler - there's no way of creating your own attribute that the C# compiler will understand as indicating that a member is obsolete. 不, ObsoleteAttribute实际上是硬编码到C#编译器中 - 没有办法创建自己的属性,C#编译器会理解这个属性表明成员已经过时了。

Personally I'd just go with ObsoleteAttribute - is it really that bad that the error message starts with "X is obsolete"? 就个人而言我只是去与ObsoleteAttribute -是不是真的那么糟糕,错误消息“X是过时的”开始?

One way to achieve what you want would be a custom post-build task . 实现您想要的一种方法是自定义post-build task After your project compiled, let another program that you created load this assembly and parse it for your attribute. 编译项目后,让您创建的另一个程序加载此程序集并解析它的属性。 You could then output the message you wand and whatever more. 然后,您可以输出您的魔杖信息等等。 But outputting the exact line number and file where this attribute is used will be tricky task, because for this you'd have to parse the pdb file (and would only work in Debug mode properly). 但输出确切的行号和使用此属性的文件将是一项棘手的任务,因为为此您必须解析pdb文件(并且只能在调试模式下正常工作)。

You should better just stick to the Obsolete attribute of .NET. 你最好坚持使用.NET的Obsolete属性。 :-) :-)

you can use only obsolete 你只能使用过时的

With Error 有错误

    [Obsolete("Hello", true)]
    public String foo() {
        return "bar";
    }

and with warning 并警告

    [Obsolete("Hello", false)]
    public String foo() {
        return "bar";
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM