在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場的方法大加讚賞:-)
谷歌顯示167萬次的結果的搜索您的錯誤信息(即「不能訪問非靜態字段在靜態情況下」,沒有雙引號) 。通常,這是一個有用的技巧:收集錯誤消息,刪除特定於您的程序的標識符(例如'_cf'),然後將剩餘的標識符提供給Google。極高的可能性是你會馬上得到答案。 – dasblinkenlight 2014-08-28 08:04:18
爲什麼混合UI.Page與ASP.MVC?如果你需要訪問當前用戶使用Session而不是HttpContext。我建議你閱讀默認模板項目爲ASP.MVC – Mario 2014-08-28 08:04:53