2013-12-17 134 views
2

僅供參考我花了大約30分鐘時間尋找答案。如果我錯過了stackoverflow,我很抱歉。這似乎是一個簡單的答案,但是我的同事都不知道。爲什麼我不能在公共靜態字符串上使用連接

我正在使用現有的庫。我試圖保持與當前系統的整合,同時增加改變一些硬編碼值的能力。我重構了代碼以利用ConfigurationManager,因此我可以使用參數化的Web部署。

我的問題是這個..爲什麼,當我訪問Constants.CourseMillRegisterURL時,我只返回部分變量?我找回的部分是從web.config中讀取的部分。我希望獲得一個包含兩個變量concat'd的完整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'](http://msdn.microsoft.com/zh-cn/library/system.uri(v = vs.110).aspx)類。 – Rik

+0

我會研究這個。老闆說'請快速解決' – CarComp

+1

雖然Bathsheba的回答當然是正確的,但這些公共靜力學是否應該是可覆蓋的?如果不是,最好將它們實現爲只讀屬性,它們立即呈現它們的順序不重要。 –

回答

7

靜態字符串按它們在文件中出現的順序進行初始化。

courseMillRegisterURLCourseMillRegisterURL後初始化,例如。

這就是爲什麼你的字符串不完整。

+0

我測試了這個,它確實解決了我的問題。謝謝。 – CarComp

相關問題