问题描述
|
我在下面使用代码,会话变量在Common类和SessionVariables结构下声明。
会话变量名的使用时间已经很长了,您是否知道如何在我的情况下最小化变量名?是否可以在不包含类名的情况下使用SessionVariables.IsLogout这样的变量名?
会话[Common.SessionVariables.IsLogout]
public class Common
{
public struct SessionVariables
{
public static string IsLogout = \"IsLogout\";
}
}
解决方法
您可以使用“ 1”别名指令。然后,您将可以在示例中以
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)
{
}
}
}