为什么我不能在struct中使用静态构造函数? [英] why i can not use static constructor in struct ?

查看:132
本文介绍了为什么我不能在struct中使用静态构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  struct 雇用
{
static string 通过;
int id;
string name;
static Employ()
{
Pass = ;
Console.WriteLine( creat static constructor Employ);
}
public 使用( string _name, int _id)
{
name = _name;
id = _id;
}
}
class 计划
{
静态 void Main( string [] args)
{
Employ Ob = new 雇用( mohamed 10 );

}
}





为什么当我从struct创建变量时使用编译器不能访问静态构造函数??

解决方案

我刚刚尝试了你发布的代码,并且 static 构造函数是正确的在调用非 static 构造函数之前调用


它肯定访问静态构造函数。但仅限于第一次创建Employ支柱实例时。如果您尝试第二次创建新实例,则无法访问。静态构造函数用于初始化任何静态数据,或执行仅需执行一次的特定操作



http://msdn.microsoft.com/en-us/library/k9x6w0hc(v = VS.80)的.aspx [ ^ ]


未调用静态构造函数,因为在Main方法中,您不引用 Employ 类的任何静态成员(参见静态构造函数 [ ^ ]: 在创建第一个实例或引用任何静态成员之前,会自动调用静态构造函数来初始化类。



更改

Quote:

static string Pass;

to

 public static string Pass; 





并将以下行添加到 Main 方法

 Console.WriteLine(Employ.Pass); 



查看静态构造函数调用。


struct Employ
    {
        static string Pass;
        int id;
        string name;
        static Employ()
        {
            Pass = "Word";
            Console.WriteLine("creat static constructor Employ ");
        }
        public Employ(string _name,int _id)
        {
            name = _name;
            id = _id;
        }
    }
class Program
    {
        static void Main(string[] args)
        {
            Employ Ob = new Employ("mohamed", 10);

        }
    }



why when i creat variable from struct employ the compiler not access the static constructor ??

解决方案

I just tried the code you posted and the static constructor is correctly called right before the non-static constructor is called.


It definitely access static constructor. But only for first time when the "Employ" strut instance is created. if you trying to create new instance second time it will not access. A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only

http://msdn.microsoft.com/en-us/library/k9x6w0hc(v=VS.80).aspx[^]


The static constructor is not called because in your Main method you don''t reference any static member of the Employ class (see Static Constructors[^]: A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.

change

Quote:

static string Pass;

to

public static string Pass;



and add the following line to your Main method

Console.WriteLine(Employ.Pass);


To see the static constructor called.


这篇关于为什么我不能在struct中使用静态构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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