如果汇编存在,则为C#条件编译

TTT*_*TTT 2 c# conditional-compilation

我有一个项目的参考可能存在,也可能不存在.我有使用该引用的代码,我只想在程序集存在时编译它.我正在考虑以下几点:

#if ASSEMBLY_EXISTS
    AssemblyClass.DoSomething();
#endif
Run Code Online (Sandbox Code Playgroud)

我可以根据需要将#define放在顶部并注释/取消注释,但我更愿意,如果没有我的手动干预,它可能只是知道它是否在那里,这让我相信#if不适用于这种情况.是否存在另一种基于程序集是否存在而有条件地编译的方法?

Ste*_*per 5

也许用MSBUILD中的条件来做;

它看起来像它

<PropertyGroup>
     <DefineConstants Condition="Exists('my.dll') ">$(DefineConstants);DLLEXISTS</DefineConstants>
</PropertyGroup>
Run Code Online (Sandbox Code Playgroud)

并且应该在你的.csproj文件中走得很远.

这大致读作"通过附加DLLEXISTS重新定义常量,如果my.dll存在"

现在你应该可以做到

#if DLLEXISTS
    // your stuff here
#endif
Run Code Online (Sandbox Code Playgroud)

您可能需要摆弄EXISTS表达式以找到合适的相对路径.