在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