Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
411 views
in Technique[技术] by (71.8m points)

optimization - How to stop C# from replacing const variable with their values?

We have a project that's compiled into a DLL called consts.dll that contains something like:

public static class Consts
{
    public const string a = "a";
    public const string b = "b";
    public const string c = "c";
}

We have multiple projects of this sort, each compiled into a DLL of the same name (consts.dll) and we replace them according to need. We have another class that uses these consts:

public class ConstsUser 
{
    string f() { return Consts.a; }
}

Unfortunately, Consts.a is optimized to "a" , so even if we replace Consts.dll implementation, we still get "a" instead of the correct value and we need to recompile ConstsUser. Is there anyway to stop the optimizer from replacing const variables with their values?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think usage of static readonly modifiers fits your needs:

public static class Consts
{
    public static readonly string a = "a";
    public static readonly string b = "b";
    public static readonly string c = "c";
}

Constants are hard-coded on the call-site, so that is your problem. Static readonly variable can be modified only in variable declaration or static constructor of Consts class, and it will not be inlined on the call-site.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...