2014-08-28 136 views
0

在Visual Studio 2010中編寫代碼時出現Cannot access non-static field _cf in static context,我得到一個錯誤,有人請解釋我爲什麼會收到此消息,如果可能的話如何解決此問題?無法訪問靜態上下文中的非靜態字段

CommonFunctions.cs

namespace WebApplication1.Functions 
{ 
    public class CommonFunctions 
    { 
     public string CurrentUser() 
     { 
      string login = HttpContext.Current.User.ToString(); 
      string[] usplit = login.Split('\\'); 
      string name = usplit[1]; 
      return name; 
     } 
    } 
} 

Team.aspx.cs

namespace WebApplication1 
{ 
    public partial class Team : System.Web.UI.Page 
    { 
     private readonly CommonFunctions _cf = new CommonFunctions(); 

     public string CurrentUser = _cf.CurrentUser(); 

     protected void Page_Load(object sender, EventArgs e) 
     { 
      if (!string.IsNullOrEmpty(CurrentUser)) 
      { 
       // Do stuff here 
      } 
      else 
      { 
       // Do other stuff here 
      } 
     } 
    } 
} 

我可以把CurrentUser碼直接進入protected void Page_Load功能,但我需要重用CurrentUser整個項目似乎可笑複製。

任何幫助將通過調用_CF場的方法大加讚賞:-)

+0

谷歌顯示167萬次的結果的搜索您的錯誤信息(即「不能訪問非靜態字段在靜態情況下」,沒有雙引號) 。通常,這是一個有用的技巧:收集錯誤消息,刪除特定於您的程序的標識符(例如'_cf'),然後將剩餘的標識符提供給Google。極高的可能性是你會馬上得到答案。 – dasblinkenlight 2014-08-28 08:04:18

+0

爲什麼混合UI.Page與ASP.MVC?如果你需要訪問當前用戶使用Session而不是HttpContext。我建議你閱讀默認模板項目爲ASP.MVC – Mario 2014-08-28 08:04:53

回答

3

在構造函數中設置東西會更有意義:

namespace WebApplication1 
{ 
    public partial class Team : System.Web.UI.Page 
    { 
     private readonly CommonFunctions _cf; 

     public string CurrentUser; 

     public Team() 
     { 
      _cf = new CommonFunctions(); 
      CurrentUser = _cf.CurrentUser(); 
     } 

     protected void Page_Load(object sender, EventArgs e) 
     { 
      if (!string.IsNullOrEmpty(CurrentUser)) 
      { 
       // Do stuff here 
      } 
      else 
      { 
       // Do other stuff here 
      } 
     } 
    } 
} 
+0

謝謝,一點點調整排序我的問題,非常感謝:-) – iggyweb 2014-08-28 10:48:11

0

不能初始化當前用戶領域。這兩個字段沒有特定的執行順序。 CurrentUser可以先初始化。

相關問題