简体   繁体   English

如何基于C#中缺少的属性生成编译器错误?

[英]How to generate a compiler error based on an attribute being missing in C#?

I create a number of add-ins for the Revit Structure API. 我为Revit Structure API创建了许多插件。 Each tool has to habe a class which implements the interface IExternalCommand. 每个工具都必须具有一个实现接口IExternalCommand的类。

In the latest version of Revit, for your tool to work you need to have two attributes on the class that implements that interface: 在最新版本的Revit中,为了使您的工具正常工作,您需要在实现该接口的类上具有两个属性:

[Regeneration(RegenerationOption.Manual)] [Transaction(TransactionMode.Automatic)] [Regeneration(RegenerationOption.Manual)] [Transaction(TransactionMode.Automatic)]

The values in brackets can change, but there must be something there. 括号中的值可以更改,但是必须有一些值。 Often I am finding myself forgetting to put the attributes on, then when it comes to runtime it crashes. 我经常发现自己忘记了放置属性,然后在运行时崩溃。 Is there any way in Visual Studio 2010 to add a compiler warning or error saying that if your class implements that interface it must have those 2 attributes? 在Visual Studio 2010中,有什么方法可以添加编译器警告或错误,指出如果您的类实现了该接口,则它必须具有这2个属性? I have resharper if that helps. 我可以帮忙。

Can anyone point me into the right direction? 谁能指出我正确的方向?

Unfortunately not. 不幸的是没有。 (I don't know about Resharper, though) (不过,我不了解Resharper)

If you have VS2010 Ultimate, you could write a custom Code Analysis rule. 如果您拥有VS2010 Ultimate,则可以编写自定义代码分析规则。

Not during compile time, but I think it'd be easy to with reflection. 不是在编译时,但我认为反射起来很容易。

I suggest a separate program that uses reflection to examine your compiled assembly, finds all classes with the specified interface, then checks attributes on those classes, returning a nice friendly error message very quickly. 我建议一个单独的程序,该程序使用反射来检查编译的程序集,查找具有指定接口的所有类,然后检查这些类的属性,并很快返回友好的错误消息。

You'd still have to run this program after you compile your program, but depending on your IDE, you could set it as a post-build step. 编译程序后,仍然需要运行此程序,但是根据您的IDE,可以将其设置为构建后的步骤。

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

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