public static void DoSomething()
{
int a;
string b;
//..do something
}
在上面的例子中,我声明了两个变量。它们是否因为包含它们的方法是静态的而变成静态的?
不行,只有方法是静态的,变量不是。
根据MSDN:
C#不支持静态局部变量(在方法作用域中声明的变量)。
如果您想在静态成员中拥有静态变量,请在静态方法之外进行声明。
private static int _var = 0;
public static void SampleMethod()
{
_var++;
}
public static byte[] RawSerialize(object anything)
{
int rawsize = Marshal.SizeOf(anything);
IntPtr buffer = Marshal.AllocHGlobal(rawsize);
Marshal.StructureToPtr(anything, buffer, false);
byte[] rawdata = new byte[rawsize];
Marshal.Copy(buffer, rawdata, 0, rawsize);
Marshal.FreeHGlobal(buffer);
return rawdata ;
}
你不能拥有本地静态变量。
C#不支持静态本地变量(在方法范围内声明的变量)。
在ASP.NET中,您可以使用System.Web.HttpContext.Current.Session创建“静态”基于会话的变量。
例如:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace SomeNameSpace
{
public static class CSession
{
private static readonly string zE = "";
private static readonly string CrLF = Environment.NewLine;
/// <summary>
///
/// </summary>
public static bool HasSession { get { return HttpContext.Current != null && HttpContext.Current.Session != null; } }
/// <summary>
/// Get a session variable
/// </summary>
/// <param name="pSessionKey"></param>
/// <returns></returns>
public static object Get(string pSessionKey)
{
object t = null;
try
{
if (HasSession && HttpContext.Current.Session[pSessionKey] != null) { t = (object)HttpContext.Current.Session[pSessionKey]; }
}
catch (Exception ex) { t = null; string m = ex.Message; }
return t;
}//object Get(string pSessionKey)
/// <summary>
/// Set a session variable
/// </summary>
/// <param name="pSessionKey"></param>
/// <param name="pObject"></param>
public static void Set(string pSessKey, object pObject)
{
if(!HasSession) { return; }
HttpContext.Current.Session.Remove(pSessKey);
HttpContext.Current.Session.Add(pSessKey, pObject);
}//void Set(string pSessionKey, object pObject)
public static string GetString(string pSessKey)
{
string sTemp = zE;
object t = Get(pSessKey);
if (t != null) { sTemp = (string)t; } else { sTemp = zE; }
return sTemp;
}//string GetString(string pSessionKey)
public static int GetInt(string pSessKey)
{
int s = 0;
object t = Get(pSessKey);
if (t != null) { s = (int)t; }
return s;
}//int GetInt(string pSessionKey)
public static Int32 GetInt32(string pSessKey)
{
Int32 s = 0;
object t = Get(pSessKey);
if (t != null) { s = (Int32)t; }
return s;
}//Int32 GetInt32(string pSessionKey)
public static bool GetBool(string pSessKey)
{
bool s = false;
object t = Get(pSessKey);
if (t != null) { s = (bool)t; }
return s;
}//bool GetBool(string pSessionKey)
}//public static class CSession
}