在 C# 类上应用属性时发出警告或报告错误
假设我定义一个属性如下。
public class LogAttribute : System.Attribute { }
并说我用它来装饰一个类,如下所示。
[Log]
public class MyClass : IMyInterface { }
我希望当我在未实现任何接口的类上应用该属性时生成编译器警告(或可能是错误)。
因此上面的代码应该不会生成任何警告,因为 MyClass 实现了 IMyInterface。
但如果该类没有实现任何接口,它应该生成警告,因此在以下情况下它应该生成警告。
[Log]
public class SomeOtherClass { }
只是想设置一个约束,即该属性只能在类实现接口时使用,否则不能使用。
我猜想 Roslyn 分析器可以实现,并且 查看这些文档但不知道从哪里开始。
有人可以轻推我或举一些例子吗?
更新
例如,我试图了解更多有关语法树的信息,我得到了以下建议。
因此我重写了方法调用。
这就是我正在寻找的。我们如何做到这一点。
我搜索了一下。我发现 此处文档中的确切警告 RS1034。
我还在这里查看了 源代码,但没有什么异常 关于它。
Say I define an attribute as follows.
public class LogAttribute : System.Attribute { }
And say I decorate a class as follows with it.
[Log]
public class MyClass : IMyInterface { }
I want a compiler warning(or may be an error) be generated when I apply that attribute on a class that does not implement any interface.
So the above should not generate any warning, because the MyClass implements IMyInterface.
But it should generate a warning if the class does not implement any interface, so it should generate a warning in the following case.
[Log]
public class SomeOtherClass { }
Simply want to put a constraint that the attribute must be used only on a class when it implements an interface and cannot otherwise.
I guess its possible with Roslyn Analyzer and was looking at these docs but not sure where to start.
Can someone nudge me or show some examples please?
Update
For example I was trying to understand more about syntax trees, I got the following suggestion.
And accordingly I rewrote the method call.
This is what I am looking for. How do we do this.
I searched a bit. I found this exact warning RS1034 in the docs here.
I also looked into the source code here, but there is nothing unusual about it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论