减少变量名称长度
本文关键字:变量名 | 更新日期: 2023-09-27 17:59:15
我使用下面的代码,会话变量在Common类和SessionVariables结构下声明。
会话变量名使用起来很长,你知道在我的情况下如何将变量名最小化吗?我可以使用像SessionVariables.IsLogout这样的变量名而不包括类名吗?
会话[Common.SessionVariables.IsLogout]
public class Common
{
public struct SessionVariables
{
public static string IsLogout = "IsLogout";
}
}
您可以使用using
别名指令。然后,您将能够访问变量SV.IsLogout
,如本例所示:
namespace Foo
{
using SV = Common.SessionVariables;
public class Common
{
public struct SessionVariables
{
public static string IsLogout = "IsLogout";
}
}
public class Example
{
public void Bar()
{
string test = SV.IsLogout;
}
}
}
为HttpSessionState
类创建扩展方法。
public static class HttpSessionStateExtensions
{
public static bool IsLoggedOut(this HttpSessionState instance)
{
return instance[Common.SessionVariables.IsLogout] == true.ToString();
}
public static bool SetIsLoggedOut(this HttpSessionState instance, bool value)
{
instance[Common.SessionVariables.IsLogout] = value.ToString();
}
}
它允许您使用(键入和所有内容):
session.IsLoggedOut();
session.SetIsLoggedOut(false);
一种方法是从Common类继承类。然后您可以直接将该变量称为SessionVariables.IsLogout.
这只是缩短的一种方法
public static class Account
{
public static int UserID
{
get { return Session[SessionVariables.UserID]; }
set { Session[SessionVariables.UserID] = value; }
}
// .... and so on
}
你可以这样使用它们:
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(Account.UserID);
}
它比一直使用Session[Sessionvariables.UserID]要短得多。
我的2美分
您可以创建一个"快捷方式类",如:
public class SesVar
{
public Common.SessionVariables IsLogout
{
get
{
return Common.SessionVariables.IsLogout;
}
}
}
然后你可以做Session[SesVar.IsLogout]
。
但就我个人而言,我不会这么做,因为这对代码的可读性不好,而且IntelliSense无论如何都会为您完成大部分打字。
您可以创建一个具有以下属性的基类:
class PageWithProperties
{
public bool IsLogout { get{ return (bool)Session["IsLogout"] }
set { Session["IsLogout"] = value; } }
}
class PageClass : PageWithProperties
{
void PageClassMethod()
{
if(IsLogout)
{
}
}
}