一个对象引用所需的非静态字段,方法或属性在我的控制 [英] An object reference is required for non-static field, method, or property in my controller

查看:409
本文介绍了一个对象引用所需的非静态字段,方法或属性在我的控制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/3775721/an-object-reference-is-required-for-the-non-static-field-method-or-property\">An对象引用是所必需的非静态字段,方法或财产

我有一个非静态字段:

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

这是我wnat以这样的动作里面是:

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";
}

编译器抱怨:

需要的对象引用用于非静态字段,方法或
  财产return语句。

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

我怎么可以参考这个领域?

How can I reference this field?

推荐答案

您不能从静态成员访问实例成员,所以你有两个选择。

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


  1. 请该方法的实例方法(删除静态关键字)

  2. 请该领域的静态(添加静态关键字)

  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.

这篇关于一个对象引用所需的非静态字段,方法或属性在我的控制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆