静态构造函数的用途是什么?

本文翻译自:What is the use of static constructors?

Please explain to me the use of static constructor. 请向我解释使用静态构造函数。 Why and when would we create a static constructor and is it possible to overload one? 为什么以及何时创建静态构造函数,并且可以重载一个?


#1楼

参考:https://stackoom.com/question/iUto/静态构造函数的用途是什么


#2楼

you can use static constructor to initializes static fields. 您可以使用静态构造函数初始化静态字段。 It runs at an indeterminate time before those fields are used. 在使用这些字段之前,它将在不确定的时间运行。 Microsoft's documentation and many developers warn that static constructors on a type impose a substantial overhead. Microsoft的文档和许多开发人员警告说,类型的静态构造函数会带来大量开销。
It is best to avoid static constructors for maximum performance. 最好避免使用静态构造函数以获得最佳性能。
update: you can't use more than one static constructor in the same class, however you can use other instance constructors with (maximum) one static constructor. 更新:同一类中不能使用多个静态构造函数,但是可以将其他实例构造函数与(最多)一个静态构造函数一起使用。


#3楼

1.It can only access the static member(s) of the class. 1.它只能访问该类的静态成员。

Reason : Non static member is specific to the object instance. 原因:非静态成员特定于对象实例。 If static constructor are allowed to work on non static members it will reflect the changes in all the object instance, which is impractical. 如果允许静态构造函数在非静态成员上工作,它将反映所有对象实例中的更改,这是不切实际的。

2.There should be no parameter(s) in static constructor. 2.静态构造函数中不应有任何参数。

Reason: Since, It is going to be called by CLR, nobody can pass the parameter to it. 原因:因为,它将由CLR调用,所以没有人可以将参数传递给它。 3.Only one static constructor is allowed. 3.只允许一个静态构造函数。

Reason: Overloading needs the two methods to be different in terms of method/constructor definition which is not possible in static constructor. 原因:重载需要这两种方法在方法/构造函数定义方面不同,这在静态构造函数中是不可能的。

4.There should be no access modifier to it. 4.应该没有访问修饰符。

Reason: Again the reason is same call to static constructor is made by CLR and not by the object, no need to have access modifier to it 原因:同样,原因是对静态构造函数的调用是由CLR而不是对象进行的,不需要对其具有访问修饰符


#4楼

Static constructors are also very useful when you have static fields that rely upon each other such that the order of initialization is important. 当您具有相互依赖的静态字段,因此初始化顺序很重要时,静态构造函数也非常有用。 If you run your code through a formatter/beautifier that changes the order of the fields then you may find yourself with null values where you didn't expect them. 如果通过更改字段顺序的格式化程序/美化程序运行代码,则可能会发现自己没有预期的空值。

Example: Suppose we had this class: 示例:假设我们有此类:

class ScopeMonitor
{
    static string urlFragment = "foo/bar";
    static string firstPart= "http://www.example.com/";
    static string fullUrl= firstPart + urlFragment;
}

When you access fullUr , it will be " http://www.example.com/foo/bar ". 当您访问fullUr ,它将是“ http://www.example.com/foo/bar ”。

Months later you're cleaning up your code and alphabetize the fields (let's say they're part of a much larger list, so you don't notice the problem). 几个月后,您正在清理代码并按字母顺序排列字段(假设它们是更大列表的一部分,因此您不会注意到问题)。 You have: 你有:

class ScopeMonitor
{
    static string firstPart= "http://www.example.com/";
    static string fullUrl= firstPart + urlFragment;
    static string urlFragment = "foo/bar";
}

Your fullUrl value is now just " http://www.example.com/ " since urlFragment hadn't been initialized at the time fullUrl was being set. fullUrl值现在只不过是“ http://www.example.com/ ”,因为urlFragment没有被当时的初始化fullUrl是被设置。 Not good. 不好。 So, you add a static constructor to take care of the initialization: 因此,您添加了一个静态构造函数来进行初始化:

class ScopeMonitor
{
    static string firstPart= "http://www.example.com/";
    static string fullUrl;
    static string urlFragment = "foo/bar";

    static ScopeMonitor()
    {
        fullUrl= firstPart + urlFragment;

    }
}

Now, no matter what order you have the fields, the initialization will always be correct. 现在,无论您以何种顺序使用字段,初始化都将始终正确。


#5楼

Static Constructor 静态构造函数

A constructor declared using static modifier is a static constructor. 使用static修饰符声明的构造函数是静态构造函数。 A static constructor is use to initialize static data or to perform a particular action that need to be performed only once in life cycle of class. 静态构造函数用于初始化静态数据或执行仅在类的生命周期中只需执行一次的特定操作。 Static constructor is first block of code to execute in class. 静态构造函数是要在类中执行的第一段代码。 Static constructor executes one and only one time in life cycle of class. 静态构造函数在类的生命周期中仅执行一次。 It is called automatically. 它被自动调用。 Static constructor does not take any parameters. 静态构造函数不接受任何参数。 It has no access specifiers. 它没有访问说明符。 It is not called directly. 它不是直接调用的。


#6楼

Why and when would we create a static constructor ...? 为什么以及何时创建静态构造函数...?

One specific reason to use a static constructor is to create a 'super enum' class. 使用静态构造函数的一个特定原因是创建一个“超级枚举”类。 Here's a (simple, contrived) example: 这是一个(简单的,人为的)示例:

public class Animals
{
    private readonly string _description;
    private readonly string _speciesBinomialName;

    public string Description { get { return _description; } }
    public string SpeciesBinomialName { get { return _speciesBinomialName; } }

    private Animals(string description, string speciesBinomialName)
    {
        _description = description;
        _speciesBinomialName = speciesBinomialName;
    }

    private static readonly Animals _dog;
    private static readonly Animals _cat;
    private static readonly Animals _boaConstrictor;

    public static Animals Dog { get { return _dog; } }
    public static Animals Cat { get { return _cat; } }
    public static Animals BoaConstrictor { get { return _boaConstrictor; } }

    static Animals()
    {
        _dog = new Animals("Man's best friend", "Canis familiaris");
        _cat = new Animals("Small, typically furry, killer", "Felis catus");
        _boaConstrictor = new Animals("Large, heavy-bodied snake", "Boa constrictor");
    }
}

You'd use it very similarly (in syntactical appearance) to any other enum: 您将在语法上将它与其他任何枚举非常相似地使用:

Animals.Dog

The advantage of this over a regular enum is that you can encapsulate related info easily. 与常规enum相比,此方法的优势在于您可以轻松封装相关信息。 One disadvantage is that you can't use these values in a switch statement (because it requires constant values). 一个缺点是您不能在switch语句中使用这些值(因为它需要常量值)。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值