在viewstate中访问变量的语法 [英] Syntax to access variables in viewstate

查看:56
本文介绍了在viewstate中访问变量的语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在回发之间保留一个变量,所以我编写了一个访问器以将其置于viewstate中.以下哪一种是访问它的最佳方式?还是有更好的选择?

I want to retain a variable between postbacks, so I write an accessor to put it into viewstate. Which one of these is the best way to access it? Or is there a better option?

选项1:

private int Status
{
    get
    {
        try
        {
            return (int)ViewState[@"__Status"];
        }
        catch
        {
            return 0;
        }
    }
    set
    {
        ViewState[@"__Status"] = value;
    }
}

选项2:

private int Status
{
    get
    {
        if (ViewState[@"__Status"] is int)
        {
            return (int)ViewState[@"__Status"];
        }
        else
        {
            return 0;
        }
    }
    set
    {
        ViewState[@"__Status"] = value;
    }
}

谢谢

我正在使用C#2.0

I'm using C# 2.0

推荐答案

这是我倾向于这样做的方式:

Here's the way that I tend to do it:

private int Status
{
  get { return (ViewState["MYSTATUS"] != null) ? (int)ViewState["MYSTATUS"] : 0; }
  set { ViewState["MYSTATUS"] = value; }
}

这篇关于在viewstate中访问变量的语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆