How to handle ((List<string>)Session.Add("")
((List<string>)S开发者_开发百科ession["answera"]).Add(xle.InnerText);
I need to perform this operation, but I get "Object reference not set to an instance of...." I don't want to use
List<string> ast = new List<string>();
ast.Add("asdas!");
Session["stringList"] = ast;
List<string> bst = (List<string>)Session["stringList"];
as I merely want to add a string to the Session-String-Array.
Have you thought about wrapping your List<string>
in a property of a custom context object? I had to do something like that on an application, so I ended up creating what was for me a UserContext
object, which had a Current
property, which took care of creating new objects and storing them in the session. Here's the basic code, adjusted to have your list:
public class UserContext
{
private UserContext()
{
}
public static UserContext Current
{
get
{
if (HttpContext.Current.Session["UserContext"] == null)
{
var uc = new UserContext
{
StringList = new List<string>()
};
HttpContext.Current.Session["UserContext"] = uc;
}
return (UserContext) HttpContext.Current.Session["UserContext"];
}
}
public List<string> StringList { get; set; }
}
I actually got most of this code and structure from this SO question.
Because this class is part of my Web
namespace, I access it much as I would access the HttpContext.Current
object, so I never have to cast anything explicitly.
If you're getting a null reference exception, it's because either the session doesn't contain the list like you think it does, or "xle" is null. Is there any reason you think the session already contains your list?
Define a property like this, and use the property instead of accessing the Session
object
public List<string> StringList
{
get
{
if (Session["StringList"] == null)
Session["StringList"] = new List<string>();
return Session["StringList"] as List<string>;
}
}
Anywhere in your app you just do:
StringList.Add("test");
You can use
((List<string>)Session["answera"]).Add(xle.InnerText);
but you have to make sure that Session["answera"]
is not null
.
Or try this way:
string[] stringArray = {"asdas"};
List<string> stringList = new List<string>(stringArray);
精彩评论