【问题标题】:In C# how can I execute a method on an object when I am using that object as a parameter?在 C# 中,当我使用该对象作为参数时,如何对该对象执行方法?
【发布时间】:2022-01-05 05:19:26
【问题描述】:

这是一个使用 .net Framework v4.8 的 asp.net webforms 应用程序

(我知道这是旧技术,我不应该用它来编写新项目。我已经十多年没有在 asp.net 中写过任何东西了,当我以这种方式编码时,使用 webforms . 我将学习 Blazor 并在未来在更现代的平台上重新编码。抱歉,我只是想阻止 cmets 中的任何“你为什么使用网络表单”。)

我在页面上有一个参数,如下所示:

        public Dictionary<string, string> StrategySubtypes {
        get
        {
            return (ViewState["StrategySubtypes"] == null) ? new Dictionary<string, string>() : (Dictionary<string, string>)ViewState["StrategySubtypes"];
        }
        set
        {
            ViewState["StrategySubtypes"] = value;
        }
    }

当我使用下面的代码在字典上调用 add 方法时,代码不会返回错误,但它也不会将新的字典项写入 ViewState。

        protected void btnAddSubtype_Click(object sender, EventArgs e)
    {
        Dictionary<string, string> tmpStrategySubtypes = StrategySubtypes;
        StrategySubtypes.Add(txtSubtype.Text, "new");
        lbSubtypes.DataSource = StrategySubtypes;
        lbSubtypes.DataTextField = "Key";
        lbSubtypes.DataValueField = "Value";
        lbSubtypes.DataBind();
        txtSubtype.Text = String.Empty;
    }

它只是进入了以太。我相信正在发生的事情是,当我调用 Add 方法时,我从 get 访问器获取 Dictionary 并在该字典上执行 add 方法,但是 Add 没有调用 set 访问器,所以我只是针对原版词典。

我正在使用以下代码解决此问题

        protected void btnAddSubtype_Click(object sender, EventArgs e)
    {
        Dictionary<string, string> tmpStrategySubtypes = StrategySubtypes;
        tmpStrategySubtypes.Add(txtSubtype.Text, "new");
        StrategySubtypes = tmpStrategySubtypes;
        tmpStrategySubtypes.GetEnumerator().Dispose();
        lbSubtypes.DataSource = StrategySubtypes;
        lbSubtypes.DataTextField = "Key";
        lbSubtypes.DataValueField = "Value";
        lbSubtypes.DataBind();
        txtSubtype.Text = String.Empty;
    }

但这似乎不优雅,而且笨拙。 必须有更好、更正确的方法来实现这一点。我的问题是,如果我使用一个对象作为公共参数,有没有办法直接在该参数上调用一个方法并让它使用 set 访问器存储结果?

【问题讨论】:

    标签: c# asp.net properties webforms accessor


    【解决方案1】:

    在 get 访问器中,如果为 null,当前代码会创建一个新字典,但它不会使用这个新字典实例设置 ViewState。因此,当您再次询问 StrategySubtypes 属性的值时,null 仍然存在并返回一个新字典。
    轻松修复:

    public Dictionary<string, string> StrategySubtypes {
    get
    {
        var dict = ViewState["StrategySubtypes"] as Dictionary<string, string>;
        if(dict == null)
        {
           dict = new Dictionary<string, string>();
           ViewState["StrategySubtypes"] = dict;
        }
        return dict;
    }
    set
    {
        ViewState["StrategySubtypes"] = value;
    }
    

    【讨论】:

    • 非常感谢!我真的觉得自己很傻。我没有更仔细地查看我的代码在做什么,而是直接得出了这样一个结论,即我无法在公共属性上执行方法。
    猜你喜欢
    • 2012-06-10
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 2019-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多