6

我已经为会话分配了一个自定义类的对象,例如:

Services Obj = getServiceDetails(3); //getting all data of Service where Id = 3
Session["ServiceObj"] = Obj;

现在我想将它的值分配给模型类中同一个类的另一个对象。我不知道该怎么做。

我试过但它不是有效的方法。:

Services oldObj = <Services>Session["ServiceObj"];

请帮助我。我不知道该怎么做。

4

6 回答 6

10

正确的类型转换需要圆括号:

Services oldObj = (Services)Session["ServiceObj"];
于 2013-05-29T06:41:41.593 回答
2

你应该使用Services oldObj = (Services)Session["ServiceObj"];

代替Services oldObj = <Services>Session["ServiceObj"];

于 2013-05-29T06:35:49.477 回答
1

您还可以使用泛型重构类型化数据检索,例如使用扩展方法,如下所示:

public static class MyExtensions
{
    public static T GetTypedVal<T>(this HttpSessionState session, string key)
    {
        var value = session[key];
        if (value != null)
        {
            if (value is T)
            {
                return (T)value;
            }
        }
        throw new InvalidOperationException(
                     string.Format("Key {0} is not found in SessionState", key));
    }
}

然后您可以将其用于引用和值类型,如下所示:

    Session["Value"] = 5;
    var valResult = Session.GetTypedVal<int>("Value");

    Session["Object"] = new SomeClass() { Name = "SomeName" };
    var objResult = Session.GetTypedVal<SomeClass>("Object");
于 2013-05-29T06:58:04.880 回答
1

像这样用你的班级投射它

Services obj = (Services)Session["ServiceObj"];
于 2013-05-29T06:38:16.000 回答
1
not <Services> use (Services) for casting
于 2013-05-29T06:37:05.290 回答
0

要从会话中获取价值,您应该对其进行转换。

Services oldObj = (Service)Session["ServiceObj"];
于 2020-07-05T16:24:35.437 回答