[英]Issue with “An object reference is required for the non-static field, method, or property” c#
I am trying to create a class with a single property which can be referenced globally within my app to store the FB access token. 我正在尝试创建一个具有单个属性的类,该类可以在我的应用程序中全局引用以存储FB访问令牌。 The code below is what I've got so far; 下面的代码是到目前为止我得到的;
public static class FBAccessTokenClass
{
private string _accessToken = "";
public static string FBAccessToken
{
get { return _accessToken; }
set { _accessToken = value; }
}
}
The above code is giving me the following error: 上面的代码给我以下错误:
An object reference is required for the non-static field, method, or property
I'm fairly new to c# and any help would be appreciated. 我是C#的新手,将不胜感激。
Just make the field static
too: 只需将字段static
:
private static string _accessToken = "";
Your property FBAccessToken
is a static property. 您的属性FBAccessToken
是静态属性。
The field _accessToken
is non-static, it's an instance field . _accessToken
字段是非静态的,它是一个实例字段 。
A static member cannot use an instance member. 静态成员不能使用实例成员。
And that makes a lot of sense: there always is exactly 1 copy of a static member but there can exist between 0 and many copies of an instance member. 这很有道理:静态成员始终完全有1个副本,但实例成员的0到许多副本之间可能存在。
The error is pretty descriptive; 该错误非常具有描述性。 you are trying to access a non-static field (_accessToken) from a static method (FBAccessToken). 您正在尝试从静态方法(FBAccessToken)访问非静态字段(_accessToken)。
The _accessToken variable belongs to the class and the class must be instantiated as an object before you can access it. _accessToken变量属于该类,并且在访问它之前必须将该类实例化为一个对象。
You can call FBAccessToken from anywhere that can access the method as it belongs to the type. 您可以从任何可以访问方法的地方调用FBAccessToken,因为它属于该类型。
Either make _accessToken static, or remove static from FBAccessToken and create an instance of the FBAccessToken class. 使_accessToken静态,或从FBAccessToken中删除静态,并创建FBAccessToken类的实例。
See http://msdn.microsoft.com/en-us/library/79b3xss3(v=vs.80).aspx for more information on static classes and members. 有关静态类和成员的更多信息,请参见http://msdn.microsoft.com/zh-cn/library/79b3xss3(v=vs.80).aspx 。
Change 更改
private string _accessToken = "";
to 至
private static string _accessToken = "";
The static keyword means that the veriable isn't bound to an object of type FBAccessTokenClass, but rather belongs to the FBAccessTokenClass type itself. 关键字static意味着该Veriable不绑定到FBAccessTokenClass类型的对象,而是属于FBAccessTokenClass类型本身。
Moreover, are you sure you should be using a static class for this? 此外,您确定应该为此使用静态类吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.