如何从与他们的价值观取代常数变量停止C#? [英] How to stop C# from replacing const variable with their values?

查看:134
本文介绍了如何从与他们的价值观取代常数变量停止C#?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个包含类似的东西被编译成DLL称为consts.dll项目:

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";
}

我们有这种多个项目,每个编译成相同的一个DLL名字(consts.dll),我们根据需要替换它们。
我们使用了这些consts其他类:

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; }
}



不幸的是, Consts.a 优化为一,所以即使我们更换Consts.dll实施,我们仍然可以得到的一,而不是正确的价值,我们需要重新编译 ConstsUser 。反正有从与他们的价值观取代了const变量阻止优化?

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?

推荐答案

我觉得的使用静态只读修饰符适合您的需要:

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";
}



常量是硬编码的通话现场,所以这是你的问题。静态只读变量只能在变量声明或的静态构造函数Consts 类进行修改,也不会在电话会议上现场进行内联。

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.

这篇关于如何从与他们的价值观取代常数变量停止C#?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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