简体   繁体   English

在没有基本关键字的情况下访问由静态变量隐藏的实例变量

[英]Accessing Instance Variable Hidden By Static Variable Without Base Keyword

How come I can't access the hidden instance variable a in the line (int gimmeValue = shinyNewBObject.a;) ? 为什么我无法访问该行中的隐藏实例变量a(int gimmeValue = ShinyNewBObject.a;)? I understand that I can use the base keyword to access the instance a. 我了解可以使用base关键字访问实例a。 However, I thought that the compiler would use the object reference in shinyNewBObject to rule out static variables. 但是,我认为编译器将使用ShinyNewBObject中的对象引用来排除静态变量。 If the static version of a is ruled out, the instance version of a would become unhidden and therefore accessible. 如果排除了a的静态版本,则a的实例版本将变为隐藏状态,因此可以访问。

What's going on here? 这里发生了什么? Did the compiler create a list of all a identities in the assembly and ruled out the instance variable because it's hidden before it ruled out the other a because it's static? 编译器是否在程序集中创建了一个所有身份的列表,并排除了实例变量,因为它是静态的,所以在隐藏另一个实例变量之前,它被隐藏了?

class A
{
    public int a;
}

class B : A
{
    new public static int a;

    public void m()
    {
        B shinyNewBObject = new B();
        int gimmeValue = shinyNewBObject.a; //Error
        gimmeValue = base.a;
    }
}

我不能完全确定C#规范的哪一部分规定了为什么子类中的静态字段遮盖了基类型变量时为什么不让您访问基类型变量,但是要解决此问题,您可以将其强制转换为A

int gimmeValue = ((A)shinyNewBObject).a; 

I think I found the answer: 我想我找到了答案:

I needed to look at the member look-up section of the specification (7.4). 我需要查看规范的成员查找部分(7.4)。

"the effect of the look-up rules is simply that derived members hide base members with the same name or signature. Such single-inheritance look-ups are never ambiguous." “查询规则的作用很简单,即派生成员隐藏具有相同名称或签名的基本成员。这样的单继承查询永远不会模棱两可。”

I think what happens when aobj.a is considered by the compiler is aobj is ignored for the time being and just a is considered. 我认为当编译器认为aobj.a是aobj时会被忽略,而只是考虑a会发生什么。

The compiler goes to the A class definition which has all of the static and instance members implicitly or explicitly and sees the two a members. 编译器转到A类定义,该类隐式或显式包含所有静态和实例成员,并查看两个a成员。 Both are accessible based on (3.5) so they go in the set of possibilities. 两者均基于(3.5)进行访问,因此它们具有多种可能性。 Then the hidden variable is removed leaving the static one. 然后,将隐藏变量删除,留下静态变量。

Finally 'aobj' is considered and an error occurs because an instance reference can't access the static variable. 最后,将考虑'aobj'并发生错误,因为实例引用无法访问静态变量。

There might be some problems with my story. 我的故事可能有一些问题。 If so, please correct me because I made some guesses. 如果是这样,请纠正我,因为我做了一些猜测。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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