在编译期间执行代码 [英] Execute code during compile time

查看:106
本文介绍了在编译期间执行代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含1个类库的项目。我有一个要求,我需要在用户编译/构建代码时使用C#代码检查某些条件。



我希望只有在我的手机连接到笔记本电脑时才能成功构建代码。如果手机未连接,则构建失败。



提前致谢。



我尝试了什么:



根据我的探索离子Goggle,我没有找到任何相关的答案来回答这个问题。

请帮忙。

I have a project which contains 1 Class Library. I have a requirement, where I need to check some condition using C# code when user compiles/builds the code.

I want code to build successfully only when my phone is connected to my laptop. If the phone is not connected, the build should fail.

Thanks in advance.

What I have tried:

Based on my exploration ion Goggle, I did not find any relevant answer to this question.
Kindly help.

推荐答案

不使用prebuild事件?单独使用Visual Studio是不可能的。正在编译的代码将不会在构建期间执行。



您必须自定义编写自己的MSBuild文件以添加可执行文件来检查您的状况并终止构建。



我没有任何例子,坦率地说,这是一个非常奇怪的要求。如果您认为这可以用来防止其他人构建您的代码,那么您就错了。 MSBuild文件只是一个文本文件,可以像任何其他文件一样编辑,您的要求可以轻松删除。



谷歌的自定义MSBuild任务并开始阅读。
Without using a prebuild event? Not possible using Visual Studio alone. The code being compiled will NOT be executed during the build.

You would have to custom write your own MSBuild file to add an executable to check your condition and terminate the build.

I don't have any examples, and, frankly, it's a very strange "requirement". If you think this can be used as some protection against someone else building your code, you're wrong. The MSBuild file is just a text file that can be edited like any other and your "requirement" can be easily removed.

Google for "Custom MSBuild Task" and start reading.


您可以使用e Pre-Build事件。例如,请参阅:快速提示:根据文件内容在Visual Studio中中止构建 - Sup-a-Dillie-O [ ^ ]
You could use e Pre-Build event. See, for instance: Quick Tip: Aborting builds in Visual Studio based on file contents – Sup-a-Dillie-O[^]


你可以使用预构建事件(项目 - 属性 - 构建事件)。



如果您有一些包含检查的C#代码,请使用该代码创建命令行应用程序返回一个合适的值。然后将其作为预构建事件执行。当返回值不为零时,将停止构建。这些事件只是批处理文件中的命令行执行。您可以检查并设置 errorlevel 或使用exit命令(其中除零以外的任何其他值将再次停止构建)。
You can use pre-build events (Project - Properties - Build Events).

If you have some C# code that contains your checks, create a command line application using that code and return an appropriate value. Then execute it as pre-build event. The build will be stopped when the return value is not zero. These events are just command line executions like within batch files. You can check and set the errorlevel or use the exit command (where any other value than zero will again stop the build).


这篇关于在编译期间执行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆