在C#中受保护的静态字符串前往的交通问题 [英] protected static string accessability issue in C#

查看:100
本文介绍了在C#中受保护的静态字符串前往的交通问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个抽象基类,它是一个模板。

 公共抽象类基地< T>其中T:新的()
{
保护静态字符串MAGIC;
}



然后我有两班从基础派生,但 T 的值不同。

 公共类Derived1:基<其他1> {} 

公共类Derived2的:基地<其它2> {}



两个奇怪的事情似乎发生。首先, Derived2.MAGIC 可从 Derived1 的成员函数内;我不希望这一点。此外, Derived2的有一个静态构造函数用于设置 MAGIC ;而当 Derived1 访问 Derived2的 Derived2的的静态构造函数不叫奇的一部分。 。MAGIC (这甚至不应该被允许)



两个问题:




  • 为什么 Derived1 访问 Derived2的一个受保护的静态成员


  • 我想任何静态成员访问之前静态构造函数中运行,为什么当我访问 Derived2.MAGIC ,我不能看到它被称为静态构造函数?




这两个似乎是严重错误。



只需添加注释,如果MAGIC是另一方面的静态受保护的功能,这个问题不存在,这使得整个事情更加清楚。

解决方案

为什么 Derived1 访问受保护的静态成员的 Derived2的




MAGIC 是一个共同的基类,而不是在 Derived2的。 T> 基础中的任子类将看到相同名称的变量,但它实际上是不同的变量,如 T 是每个派生类不同。




我还以为被访问的任何静态成员之前,静态构造函数中运行,为什么当我访问 Derived2.MAGIC ,我是没有看到它被称为静态构造函数?




有没有申报 Derived2.MAGIC ,有一个声明基地< T> .MAGIC Derived1 正在访问在其自己的基类中声明受保护的领域。



您是从一个假设,即MAGIC是开始在 Derived2的声明。如果你改变你的代码,以便实际上的情况下,您的期望将举行。


I have an abstract base class which is a templated.

public abstract class Base<T> where T : new()
{
     protected static string MAGIC;
}

I then have a two classes which derive from Base, but with different values of T.

public class Derived1:Base<Other1> {}

public class Derived2:Base<Other2> {}

Two odd things seem to be happening. First of all, Derived2.MAGIC is available from within a member function of Derived1; I would not expect that. Additionally, Derived2 has a static constructor which sets MAGIC; the odd part being that Derived2's static constructor is not called when Derived1 accesses Derived2.MAGIC (which shouldn't even be allowed).

Two questions:

  • Why can Derived1 access a protected static member of Derived2?

  • I thought static constructors were run before any static members were accessed, why when I access Derived2.MAGIC, am I not seeing it's static constructor called?

Both of these seem to be serious bugs.

Just adding a note that if MAGIC was on the other hand a static protected function, this problem does not exist, which makes the whole thing even more unclear.

解决方案

Why can Derived1 access a protected static member of Derived2?

MAGIC is in a common base class, not in Derived2. Any subclass of Base<T> will see a variable of the same name, though it will actually be different variables if T is different for each derived class.

I thought static constructors were run before any static members were accessed, why when I access Derived2.MAGIC, am I not seeing it's static constructor called?

There is no declaration Derived2.MAGIC, there is a declaration Base<T>.MAGIC. Derived1 is accessing a protected field declared in its own base class.

You are starting from an assumption that MAGIC is declared in Derived2. If you change your code so that's actually the case, your expectations will hold.

这篇关于在C#中受保护的静态字符串前往的交通问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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