判断这个很简单,就是从内存的优化方面去考虑.因为静态和非静态的不同的地方,就是静态的从程序一启动就会一直占用内存,而非静态的只在使用后(实例化)后才会占用内存.但是每实例化个一个对象时又会另外占用内存. 举个例子,比如说一个数据库的连接字段(STRING).因为要经常使用到它,这时我们可以用STATIC.但是如果这时用非静态的话那就不合算了,因为每次调用到它时,又实例化一次.这样相比来说占用内存就比较大了.不划算. 像一个登录后台的方法,你只在登陆时候调用一次,就没有必要做成静态的了.那样一直驻存在内存中.在大型项目中,你如果都使用静态的那得要多少内存去支撑呀.嘿嘿 简单点,就是它经常要被调用时,就用静态的.相反则用非静态的.
那也就是说,公共方法就设置为静态的方法呗。果然是的,看经常用的comm类就是静态的Static
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
|
public class fnComm { public static JObject Post(HttpClient myhttp, string url, JObject json) { HttpContent content = new StringContent(JsonConvert.SerializeObject(json), Encoding.UTF8, "application/json" ); var message = Task<HttpResponseMessage>.Run<HttpResponseMessage>(() => { return myhttp.PostAsync(url, content); }); message.Wait(); //接收返回得信息 if (message.Result.IsSuccessStatusCode) { var s = Task.Run(() => { return message.Result.Content.ReadAsStringAsync(); }); s.Wait(); return JObject.Parse(s.Result); } else { throw new Exception( "StatusCode:" + message.Result.StatusCode.ToString()); } } public static byte [] ConvertToByteAry( object obj) { var j = JsonConvert.SerializeObject(obj); var ary = System.Text.Encoding.UTF8.GetBytes(j); return ary; } /// <summary> /// datetime转换为unixtime /// </summary> /// <param name="time"></param> /// <returns></returns> public static int TimeToUnixTime(System.DateTime time) { return ( int )(time - new DateTime(1970, 1, 1).ToLocalTime()).TotalSeconds; } public static string GenerateTransId( int i) { string transId = DateTime.Now.ToString( "yyyyMMddHHmmss" ); int l = i - 14; return transId + CreateRandCode(l); } public static string CreateRandCode( int codeLen) { string codeSerial = "1,2,3,4,5,6,7,a,c,d,e,f,h,i,j,k,m,n,p,r,s,t,A,C,D,E,F,G,H,J,K,M,N,P,Q,R,S,U,V,W,X,Y,Z" ; if (codeLen == 0) { codeLen = 16; } string [] arr = codeSerial.Split( ',' ); string code = "" ; int randValue = -1; Random rand = new Random( unchecked (( int )DateTime.Now.Ticks)); for ( int i = 0; i < codeLen; i++) { randValue = rand.Next(0, arr.Length - 1); code += arr[randValue]; } return code; } public static string GetStringFromList(List< string > list) { StringBuilder sb = new StringBuilder(); string strReturn; if (list.Count > 0) { foreach ( string item in list) { sb.AppendFormat( "'{0}'," , item); } strReturn = sb.ToString(0, sb.Length - 1); } else { strReturn = "''" ; } return strReturn; } } |
以上就是c# 静态类的使用场景的详细内容,更多关于c# 静态类的资料请关注服务器之家其它相关文章!
原文链接:https://www.cnblogs.com/ZkbFighting/p/14106785.html