首页 新闻 会员 周边 捐助

诡异的静态构造函数

0
悬赏园豆:5 [已解决问题] 解决于 2011-01-08 10:48

public class Rational

{

protected static Rational one;
public static Rational One
{
get { return one; }
}
protected static Rational zero;
public static Rational Zero
{
get { return zero; }
}

{

public int N { get; set; }
public int M { get; set; }
static Rational()
{
one = new Rational(1, 1);
zero = new Rational(0, 1);
}
public Rational(int n, int m)
{
N = n;
M = m;
}
public override string ToString()
{
return string.Format("{0}/{1}", N, M);
}
}

static void Main(string[] args)
{
  Rational r1 = Rational.One;//r1 is 1/1
Rational r2 = Rational.Zero;//r2 is 0/1
Rational r = new Rational(1, 2);
  Rational r3 = Rational.One;//r3 is 1/1
  Rational r4 = Rational.Zero;//r4 is 0/1
}
 但是:

public class Ra
{
protected static Rational one;
public static Rational One
{
get { return one; }
}
protected static Rational zero;
public static Rational Zero
{
get { return zero; }
}
}

public class Rational:Ra
{

public int N { get; set; }
public int M { get; set; }
static Rational()
{
one = new Rational(1, 1);
zero = new Rational(0, 1);
}
public Rational(int n, int m)
{
N = n;
M = m;
}
public override string ToString()
{
return string.Format("{0}/{1}", N, M);
}
}

 

static void Main(string[] args)
{
  Rational r1 = Rational.One;//r1 is null
  Rational r2 = Rational.Zero;//r2 is null
Rational r = new Rational(1, 2);
  Rational r3 = Rational.One;//r3 is 1/1
  Rational r4 = Rational.Zero;//r4 is 0/1
}
字段在类中,静态构造函数会在第一次调用属性之前调用初始化静态字段,但是字段继承于基类,静态构造不会在调用属性之前初始为,而是在实例化类之后初始化,什么原因,什么解决办法?

Univ的主页 Univ | 菜鸟二级 | 园豆:205
提问于:2010-12-23 22:36
< >
分享
最佳答案
0

因为static 和Instance一点关系都没有,你在Rational r1 = Rational.One;//r1 is null 的时候,其实是

Rational r1 = Ra.One;//r1 is null,One属于Ra类的成员,JIT根本不需要加载Rational的任何代码,因此Rational中的Static根本不会执行。

收获园豆:5
沉默的糕点 | 小虾三级 |园豆:1786 | 2010-12-23 23:34
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册