嵌套类:无法访问静态情况下的非静态字段 [英] Nested class: Cannot access non-static field in static context

查看:290
本文介绍了嵌套类:无法访问静态情况下的非静态字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些内部变量C类。它有希望访问C.变量无论是C和N分别静态嵌套类N,虽然C有一些静态方法和变量。当我试图访问一个非静态变量用C从NI获得波浪下划线和消息无法访问非静态字段[字段名]在静态情况下。



这似乎有事情做与嵌套类,因为我可以访问从封闭类本身变细。



ReSharper的建议我做_t静态的,而是说ISN T选项。 ?我该如何处理这种



 公共部分的密封类C 
{
串_t;

类N
{
无效米()
{
_t =外商投资企业; //这里出现错误
}
}
}


解决方案

这是不是Java,而你没有的的类。



的一个实例嵌套类不与外部类的任何实例相关联的,除非你通过存储引用(又名处理/指针)在构造函数中进行关联。

 公共部分的密封类C 
{
串_t;

类N
{
只读Ç外;

公共N(父){外=父母; }

无效米()
{
outer._t =外商投资企业; //错误走了
}
}
}


I have a class C with some internal variables. It has a nested class N that wants to access the variables in C. Neither C nor N are static, although C has some static methods and variables. When I try to access a non-static variable in C from N I get the squiggly underline and the message "Cannot access non-static field [fieldname] in static context".

This seems to have something to do with the nested class, since I can access the variable fine from the enclosing class itself.

ReSharper suggests I make _t static but that isn't an option. How do I deal with this?

public sealed partial class C
{
    string _t;

    class N
    {
        void m()
        {
            _t = "fie"; // Error occurs here
        }
    }
}

解决方案

This isn't Java, and you don't have inner classes.

An instance of a nested class is not associated with any instance of the outer class, unless you make an association by storing a reference (aka handle/pointer) inside the constructor.

public sealed partial class C
{
    string _t;

    class N
    {
        readonly C outer;

        public N(C parent) { outer = parent; }

        void m()
        {
            outer._t = "fie"; // Error is gone
        }
    }
}

这篇关于嵌套类:无法访问静态情况下的非静态字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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