简体   繁体   English

C#编译器是否可以在编译时插入每次使用时自动递增的常量值?

[英]Can the C# compiler insert constant values that auto-increment on each usage at compile time?

Is there a way to have the C# compiler insert constant values that auto-increment at compile time? 有没有办法让C#编译器插入在编译时自动递增的常量值?

Eg 例如

MyFunc(NEXT_CONSTANT);
MyFunc(NEXT_CONSTANT);
MyFunc(NEXT_CONSTANT);

Would produce this code: 会产生这样的代码:

   MyFunc(1);
   MyFunc(2);
   MyFunc(3);

No, there's nothing in the language that does this. 不,语言中没有任何内容可以做到这一点。

There are some grotty hacks that would allow you to keep track of the caller file/line/member, and auto-increment based on that (if you're using C# 5) - but it wouldn't really be the same. 有些粗俗的黑客可以让你跟踪调用者文件/行/成员,并根据它自动增加(如果你使用的是C#5) - 但它实际上并不相同。

There are tool-based approaches to this which would transform your source code - but I would try to take a step back and look at your real requirements and intentions (which we don't know at the moment) and try to find a solution within the language if you can. 有基于工具的方法来此这将改变你的源代码-但我会试着退后一步,看看你的实际需求和意图(我们不知道此刻),并试图找到解决如果可以的话。

There is one such thing that does that - the build number of the assembly version. 有一个这样的事情 - 汇编版本的内部版本号。 If you set the assembly version to eg 1.2.* , the last two numbers will be changed with each build. 如果将程序集版本设置为例如1.2.* ,则每个构建将更改最后两个数字。 You can read that in your code easily - it isn't a constant, but if you expose it through a static property, it might work just fine. 您可以轻松地在代码中阅读它 - 它不是常量,但如果您通过静态属性公开它,它可能会正常工作。

If that's not enough, just make a custom build target. 如果这还不够,只需制作一个自定义构建目标。 It shouldn't be hard to maintain an almost empty C# file with a fixed structure that you can modify prior to each build. 使用可在每次构建之前修改的固定结构维护几乎为空的C#文件应该不难。

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

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