c# - 为什么我不能在公共(public)静态字符串上使用串联

标签 c# string static concatenation

仅供引用,我花了大约 30 分钟寻找答案。如果我在 stackoverflow 上错过了它,我很抱歉。这似乎是一个简单的答案,但我的同事都不知道。

我正在使用现有的图书馆。我试图保持与当前系统的集成,同时增加更改一些硬编码值的能力。我重构了代码以利用 ConfigurationManager,因此我可以使用参数化 Web 部署。

我的问题是……为什么当我访问 Constants.CourseMillRegisterURL 时,我只取回了变量的一部分?我得到的部分是从 web.config 中读取的部分。我希望得到一个包含两个变量的完整 URL,但我只得到我的 web.config 值“userlogin.jsp”。

我也尝试过对其进行编码,以便在私有(private)中连接值,但它也不会那样工作。我真的很想继续使用 static,因为整个库都使用像

这样的代码来引用这个类
string theUrl = Constants.CoursMillUrl + Constants.CourseMillRegisterUrl

每个变量返回以下内容:

为什么我的值(value)观不对

我的代码如下。

namespace STTI.CourseMill.Library
{
    #region

    using System.Configuration;

    #endregion

    public static class Constants
    {
        // prod 

        #region Static Fields

        public static string CourseMillRegisterURL = CourseMillURL + courseMillRegisterURL;

        public static string CourseMillURL = courseMillURL;

        public static string CourseMillUserLoginURL = CourseMillURL + courseMillUserLoginURL;

        #endregion

        #region Properties

        private static string courseMillRegisterURL
        {
            get
            {
                string output = ConfigurationManager.AppSettings["CourseMillRegisterUrl"];
                if (output == null)
                {
                    output = "sttilogin.jsp?d=t";
                }

                return output;
            }
        }

        private static string courseMillURL
        {
            get
            {
                string output = ConfigurationManager.AppSettings["CourseMillURL"];
                if (output == null)
                {
                    output = "http://hardcodedvalue/cm6/cm0670";
                }

                if (!output.EndsWith("/"))
                {
                    output += "/";
                }

                return output;
            }
        }

        private static string courseMillUserLoginURL
        {
            get
            {
                string output = ConfigurationManager.AppSettings["CourseMillLoginUrl"];
                if (output == null)
                {
                    output = "sttilogin.jsp?d=t";
                }

                return output;
            }
        }

        #endregion
    }
}

最佳答案

静态字符串按照它们在文件中出现的顺序进行初始化。

例如,

courseMillRegisterURLCourseMillRegisterURL 之后初始化。

这就是您的字符串不完整的原因。

关于c# - 为什么我不能在公共(public)静态字符串上使用串联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20636198/

相关文章:

c# - 在 WPF DataGrid 控件中设置选定单元格的样式

c# - 遍历 string[] List<string> 按字母顺序获取结果

c++ - 使用多个空格 (>1) 作为分隔符使用 C++ 或 linux 将行分隔为列

sql - 迭代器的MySQL实现

java - 从父类(super class) static main 创建子类

python - 带有 CKEditor 的 Django 2.0.1 在管理页面上不起作用

c# - DataBindings.Add 使用 IFormatProvider

c# - StructureMap 动态加载插件 Dll

python - re.sub python 收集高度

c - 重复调用的函数中的静态变量 C