简体   繁体   中英

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?

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.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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