An object reference is required for non-static fie

2020-03-25 06:59发布

问题:

This question already has answers here:
Closed 7 years ago.

Possible Duplicate:
An object reference is required for the non-static field, method, or property

I have a non-static field:

private IDictionary<string, string> _mappings = 
    new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase)

that I wnat to use inside of a action like this:

public static string GetMimeType(string extension)
{
    //...
    return _mappings.TryGetValue(extension, out mime) ? 
        mime : "application/octet-stream";
}

The compiler is complaining:

An object reference is required for non-static field, method, or property in the return statement.

How can I reference this field?

回答1:

You cannot access instance members from static members so you have 2 choices.

  1. Make the method an instance method (remove the static keyword)
  2. Make the field a static (add the static keyword)

The one you choose will depend on whether the field should be shared across all instances or not.



回答2:

I think the compiler is pretty clear here: Your GetMimeType method is a static method, but the _mappings variable is not declared static (an non-static or instance field/variable).

If you want to use the mappings variable as it appears above do this:

private static IDictionary<string, string> _mappings = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase)

Edit: As the commenter pointed out below, you must be careful that this is actually the behavior you want. A static member means all instances will share this same mappings variable and can overwrite the data present. If you want one mappings variable per class, then you should change your method to an instance method (by removing the static keyword), as noted in the answer above.



回答3:

If you just want a dictionary of values that is populated once and never modified after that, a thing you could do would be make the dictionary static and populate it in a static constructor.