This article will focus on c # static methods and instance methods. For some ideas, such as: "static method is resident memory", and "static method is loaded first than instance method" for analysis. We also discuss when to use static methods and instance methods.
A few days ago, a friend from Microsoft sent me a link: Do you know the difference between static methods and instantiation methods? Welcome to the discussion !! -The final question is..., and some points here need to be clarified. I hope to write a blog. I read this blog at the time. The article is short. I have listed several cases of static methods and instance methods, and I have no arguments. Then I will discuss them. Later comments are much more lively than blogs. The words were fierce. Later, the author simply deleted the blog. This blog is no longer visible. Now I am writing this blog. One is to make an analysis of some points of view, and the other is to fulfill the trust of friends.
C # static methods and instance methods
See the following code: We should have used these three forms.
01
public
class
SomeClass
02
{
03
private
string
myfield =
null
;
04
public
static
instance =
new
SomeClass();
05
public
instranceMethod() {};
06
public
static
staticMethod() {};
07
}
08
09
public
class
AnotherClass
10
{
11
public
static
Main()
12
{
13
// The first method is to declare the instance and call the instance method.
14
SomeClass someClass =
new
SomeClass();
15
someClass.instanceMethod();
16
17
// Method 2: Call the instance method through a static instance
18
SomeClass.instance.instanceMethod();
19
20
// Method 3: directly call the static method
21
SomeClass.staticMethod();
22
}
23
}
These methods differ in call time, thread security, and object-oriented programming. It will be discussed later.
"The static method is resident memory"
This is the opinion of the blog author in his comment. I think the "static method is resident memory" statement is incorrect. You need to know that a. net Type Static Method belongs to this. net type. This. net type is part of a. net assembly. This. net assembly is loaded into the memory by an AppDomain. This AppDomain can be detached from the memory. There can be more than one AppDomain in a process with. net CLR, And the AppDomain after the first AppDomain can be dynamically created and uninstalled. The. net assembly in these AppDomains can have both static methods and instance methods. Both static and instance methods are created and uninstalled along with the AppDomain of the Assembly. The first AppDomain will be uninstalled at the end of the entire program. The. net assembly is also uninstalled. See Figure 1 to better understand. So the static method does not have resident memory.