为什么不能在公共静态字符串上使用连接运算符

4

FYI,我花了大约30分钟搜索答案。如果我错过了stackoverflow上的答案,那么我很抱歉。这似乎是一个简单的答案,但我的同事们也不知道。

我正在使用现有库进行工作。我试图在保持与当前系统集成的同时,添加更改一些硬编码值的能力。我重构了代码,利用ConfigurationManager来使用参数化Web部署。

我的问题是...为什么当我访问Constants.CourseMillRegisterURL时,我只收到变量的一部分?我得到的部分是从web.config中读取的。我期望得到一个包含两个变量连接的完整URL,但我只得到我的web.config值"userlogin.jsp"。

我也尝试过在私人领域中编写代码,以便将值连接起来,但那样行不通。我真的想保持静态状态,因为整个库都使用像这样的代码引用这个类

string theUrl = Constants.CoursMillUrl + Constants.CourseMillRegisterUrl

每个变量返回以下内容: 为什么我的值不是: 我的代码如下。
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
    }
}

4
不是回答你的问题,但不要使用字符串拼接来组合URL。相反,应该使用 System.Uri 类。 - Rik
我会调查一下。老板说“请尽快修复”。 - CarComp
1
虽然Bathsheba的答案肯定是正确的,但这些公共静态变量是否应该被覆盖?如果不是,最好将它们实现为只读属性,这将立即使它们的顺序无关紧要。 - Jan Van Herck
1个回答

9

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

例如,在CourseMillRegisterURL之后才会初始化courseMillRegisterURL

这就是为什么你的字符串不完整的原因。


我测试了一下,它确实解决了我的问题。谢谢。 - CarComp

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接