如何初始化静态属性是从基类派生的。 [英] How to initial static property is derived from base class.

查看:65
本文介绍了如何初始化静态属性是从基类派生的。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何初始化静态属性是从基类派生的,如下面的代码。



How to initial static property is derived from base class as below code.

class A
      {
            protected static string keyName { get; set; }

            static A()
            {
                  Initial();
            }
            public static void Initial()
            {
               
                 string a = keyName;
                
            }
      }

class B:A
      {
         
            static B()
            {
                  keyName = "NewId";
            }

        
      }





我的尝试:



我想在初始函数中获取变量keyName的值。



What I have tried:

I want to get value of variable keyName in Initial function.

推荐答案

问题是你不能这样做的:在第一次使用B的实例之前,不会调用B的 static 构造函数。

所以如果是构造A的实例:

The problem is that you can't do that: the static constructor for B is not called until an instance of B is first used.
So if an instance of A is constructed:
A a = new A();

然后 keyName 属性的值永远不会被初始化(因此 null )。

解决这个问题的一种方法是将 A 声明为 abstract ,这会阻止正在构造A的实例,但即使这样, A 的构造函数也会在 B 的构造函数之前调用(就像你一样)我希望, A 必须在 B 可以使用之前完成)这将是stil l表示 keyName 未在初始被调用之前初始化。



你不能做你想做的事:它是不可能的,因为类 A 构造函数必须在任何派生类构造函数代码可以执行 - 这同样适用于实例和静态构造函数。



你想要实现的是什么?需要这个?

Then the value of the keyName property is never initialized (and thus null).
One way to get round this - sort of - would be to declare the class A as abstract, which would prevent instances of A being constructed, but even then the constructor for A will be called before the constructor for B (as you would expect, A has to be "complete" before B can use it) which would still mean that keyName is not initialised before Initial is called.

You can't do what you want: it just isn't possible because the class A constructor has to be complete before any derived class constructor code can be executed - and that applies equally to instance and static constructors.

What are you trying to achieve that you think you need this?


这篇关于如何初始化静态属性是从基类派生的。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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