简体   繁体   English

如果程序集存在,则执行C#条件编译

[英]C# conditional compilation if assembly exists

I have a project with a reference that may or may not exist. 我有一个参考可能存在或不存在的项目。 I have code that uses that reference and I'd like to compile it only if the assembly exists. 我有使用该引用的代码,并且仅在程序集存在的情况下才想对其进行编译。 I'm thinking something along the lines of: 我在考虑以下方面:

#if ASSEMBLY_EXISTS
    AssemblyClass.DoSomething();
#endif

I could put a #define at the top and comment/uncomment as needed, but I'd prefer if it could just somehow know if it's there without my manual intervention, which leads me to believe that #if won't work for this situation. 我可以将#define放在顶部,并根据需要添加评论/取消评论,但我希望它能在某种程度上无需我的手动干预就知道它是否在那里,这使我相信#if在这种情况下不起作用。 Is there another way to conditionally compile based on whether an assembly exists? 有没有其他方法可以根据程序集是否存在来有条件地进行编译?

Maybe do it with a condition inside MSBUILD; 也许用MSBUILD内部的条件来完成;

It would look something like it 看起来像这样

<PropertyGroup>
     <DefineConstants Condition="Exists('my.dll') ">$(DefineConstants);DLLEXISTS</DefineConstants>
</PropertyGroup>

and should go quite far down in your .csproj file. 并且应该在您的.csproj文件中走得很远。

This reads, roughly, as "redefine the constants by appending DLLEXISTS, if my.dll exists" 粗略地读为“如果存在my.dll,则通过附加DLLEXISTS来定义常量”

Now you should be able to do 现在您应该可以

#if DLLEXISTS
    // your stuff here
#endif

You might need to fiddle around with the EXISTS expression to find an appropriate relative path. 您可能需要弄乱EXISTS表达式来找到合适的相对路径。

No you cannot do this. 不,你不能这样做。 You cannot define the result of a conditional compilation symbol at compile time. 您不能在编译时定义条件编译符号的结果。

If you want to get fancy you could write a new program which detects the missing assembly and modifies your source. 如果想花哨的话,可以编写一个新程序来检测缺少的程序集并修改源代码。 You can then execute this program in the Pre-build event of your project. 然后,您可以在项目的Pre-build事件中执行该程序。

The modification of the source could simply be the addition or removal of your suggested #define at the top of the source files. 对源代码的修改可以只是在源文件顶部添加或删除建议的#define。

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

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