简体   繁体   English

C#引用具有相同名称的局部变量的静态字段

[英]C# referencing static field with like-named local variable

In a rather limiting context I need to reference a static class field from a constructor that has a variable named with the same name as the static field. 在相当有限的上下文中,我需要从构造函数引用静态类字段,该构造函数具有与静态字段同名的变量。 Here is an example to illustrate, which also includes a non-static field to highlight the fact that for non-static fields one can use "this" to reference the class-field: 下面是一个示例,其中还包括一个非静态字段,以突出显示对于非静态字段,可以使用“this”来引用类字段:

public class Example () {

    private static DateTime firstInstance;
    private static DateTime referenceInstance;

    private String Name;

    static Example() {
        first=DateTime.Now;
    }

    public Example(String Name, DateTime referenceInstance) {
        this.Name=Name;
        referenceInstance=referenceInstance;
    }
}

How can one access the "referenceInstance" static field without the "this" keyword as one does with "Name"? 如何在没有“this”关键字的情况下访问“referenceInstance”静态字段与“Name”一样? In a perfect world I would just refactor either the class variable or the constrictor variable to have a different identifier, however for a rather technical reason (printing documentation) neither can be changed here. 在完美的世界中,我只是重构类变量或缩限变量以具有不同的标识符,但是出于技术原因(打印文档),这里都不能更改。

Thanks. 谢谢。

Fully qualify the static variable name in the constructor. 完全限定构造函数中的静态变量名称。

public Example(String Name, DateTime referenceInstance) {
 this.Name=Name;
 Example.referenceInstance=referenceInstance;
}

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

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