简体   繁体   中英

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. 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.

Just make the field static too:

  private static string _accessToken = "";

Your property FBAccessToken is a static property.
The field _accessToken is non-static, it's an instance field .

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.

The error is pretty descriptive; you are trying to access a non-static field (_accessToken) from a static method (FBAccessToken).

The _accessToken variable belongs to the class and the class must be instantiated as an object before you can access it.

You can call FBAccessToken from anywhere that can access the method as it belongs to the type.

Either make _accessToken static, or remove static from FBAccessToken and create an instance of the FBAccessToken class.

See http://msdn.microsoft.com/en-us/library/79b3xss3(v=vs.80).aspx for more information on static classes and members.

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.

Moreover, are you sure you should be using a static class for this?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM