An object reference is required for non-static fie

2020-03-25 06:10发布

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?

3条回答
祖国的老花朵
2楼-- · 2020-03-25 06:42

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.

查看更多
够拽才男人
3楼-- · 2020-03-25 06:53

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.

查看更多
叛逆
4楼-- · 2020-03-25 06:58

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.

查看更多
登录 后发表回答