简体   繁体   English

在静态类中如何调用该方法

[英]How is the method called in static class

My code is as follows 我的代码如下

   class MyStaticClass
   {

     static MyStaticClass{};

    public static readonly MyStaticClass Instance = CreateMe();
    public static int GetSomeValue = GetValue();

    private static int GetValue()
    {
        return 0;
    }

    private static MyStaticClass CreateMe()
    {
        Console.WriteLine("This method was called");
        return new MyStaticClass();
    }

}

public class Program { 公共课程计划{

    public static void Main()
    {

         int val=MyStaticClass.GetSomeValue;

    }
 }

O/p: O / P:

This method was called

When I call val why does the debugger accesses CreateMe method ? 当我调用val ,调试器为何访问CreateMe方法? Is it that any static method I access it will access all the static methods in the class ? 是我访问的任何静态方法都可以访问该类中的所有静态方法吗?

The method CreateMe() is called because you are calling in when you create object Instance in the following statement. 之所以调用CreateMe()方法,是因为在以下语句中创建对象Instance时正在调用。

 public static readonly MyStaticClass Instance = CreateMe();

This is static object in your class and is created as you access the class which you did by MyStaticClass.GetSomeValue . 这是您的类中的静态对象,并且在您访问MyStaticClass.GetSomeValue所做的类时创建。

Dubugging the code will give you clear view of the order of the statements get executed. 调试代码将使您清楚地了解语句的执行顺序。 You can go through this detailed article on MSDN regarding debugging Debugger Roadmap 您可以在MSDN上阅读有关调试Debugger Roadmap的这篇详细文章

You have a static initializer for a static field. 您有一个用于静态字段的静态初始化程序。 As part of program startup, all static fields are evaluated. 作为程序启动的一部分,将评估所有静态字段。

Edit: small clarification here: 编辑:这里的小澄清:

The static fields in a particular class are evaluated in declaration order, but there in no particular order for which class has it's static fields initialized first. 特定类中的静态字段按声明顺序求值,但是对于哪个类而言,首先要初始化其静态字段的顺序没有特定的顺序。 Now, if you had a static property, that would be different. 现在,如果您具有静态属性,那将有所不同。

MSDN link MSDN链接

Both fields have been initialized using the static methods. 这两个字段均已使用静态方法初始化。 So, in that case, all the static methods will be evaluated. 因此,在这种情况下,将评估所有静态方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM