2014-08-28 137 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可以先初始化。

相关问题