Har*_*aid 3 c# asp.net extension-methods
有时我们访问Session["key"].ToString()它会在会话过期时出现异常并且在编码时我们尝试访问会话变量.所以我正在尝试在object类上创建扩展方法,以便我可以像Session["key"].getString()编码一样编写它,这样每次我都不必这样做Convert.ToString(session["key"])
任何其他解决方案也是可观的.
public static class ObjectExtensions
{
public static string GetString(this object o)
{
if (o == null)
{
return string.Empty;
}
return Convert.ToString(o);
}
}
Run Code Online (Sandbox Code Playgroud)
然后:
string value = Session["key"].GetString();
Run Code Online (Sandbox Code Playgroud)
或检查这一个:
public static class SessionExtensions
{
public static string GetString(this HttpSessionStateBase session, string key)
{
if (session == null)
{
return string.Empty;
}
var value = session[key];
if (value == null)
{
return string.Empty;
}
return Convert.ToString(value);
}
}
Run Code Online (Sandbox Code Playgroud)
然后:
string value = Session.GetString("key");
Run Code Online (Sandbox Code Playgroud)
只需使用null-coalescing运算符:
string value = (session["key"] ?? String.Empty).ToString();
Run Code Online (Sandbox Code Playgroud)
更新
如果您必须具有执行此操作的方法(扩展名或其他方式),我将执行以下操作:
public static string GetValue(this HttpSessionState session, string key)
{
// TODO: Insert appropriate error checking here.
return (session[key] ?? String.Empty).ToString();
}
Run Code Online (Sandbox Code Playgroud)
我什至可以通过GetValue使用选择器然后使用lambdas 的调用使它对于其他可能的类型通用:
public static T GetValue<T>(this HttpSessionState session, string key, Func<object, T> valueSelector)
{
return valueSelector(session[key]);
}
public static string GetStringValue(this HttpSessionState session, string key)
{
return session.GetValue(key, x => (x ?? String.Empty).ToString());
}
Run Code Online (Sandbox Code Playgroud)
然后,您将使用以下方法:
string value = session.GetStringValue("key");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5707 次 |
| 最近记录: |