在C#中受保护的静态字符串前往的交通问题 [英] protected static string accessability issue in 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 ofT
.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 ofDerived1
; I would not expect that. Additionally,Derived2
has a static constructor which setsMAGIC
; the odd part being thatDerived2
's static constructor is not called whenDerived1
accessesDerived2.MAGIC
(which shouldn't even be allowed).Two questions:
Why can
Derived1
access a protected static member ofDerived2
?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 ofDerived2
?
MAGIC
is in a common base class, not inDerived2
. Any subclass ofBase<T>
will see a variable of the same name, though it will actually be different variables ifT
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 declarationBase<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屋!