【问题标题】:how to set Key-value pair on .CS side?如何在 .CS 端设置键值对?
【发布时间】:2013-04-24 07:14:26
【问题描述】:

我找到了一种使用键值的解决方案,但问题是当我在 .Cs 上使用它时 MyUserControl1.Param.Key = "区域"; MyUserControl1.Param.Value = 面积

它不允许我这样做...下面是代码...

public partial class MyUserControl : System.Web.UI.UserControl
{
    private Dictionary<string, string> labels = new Dictionary<string, string>();

    public LabelParam Param
    {
        private get { return null; }
        set
        { 
            labels.Add(value.Key, value.Value); 
        }
    }

    public class LabelParam : WebControl
    {
        public string Key { get; set; }
        public string Value { get; set; }

        public LabelParam() { }
        public LabelParam(string key, string value) { Key = key; Value = value; }
    }
}
If I use it aspx page like below it work fine:

<%@ Register src="MyUserControl.ascx" tagname="MyUserControl" tagprefix="test" %>

<test:MyUserControl ID="MyUserControl1" runat="server">
    <Param Key="d1" value="ddd1" />
    <Param Key="d2" value="ddd2" />
    <Param Key="d3" value="ddd3" />
</test:MyUserControl>

【问题讨论】:

  • 发布尝试使用该属性的代码?阅读:stackoverflow.com/questions/2257829/…
  • 只有公共 setter 和私有 getter 实现且始终返回 null 的属性是代码异味。只需创建一个 SetParam 方法即可。
  • 我也公开了 getter,但仍然无法将值设置为 'param'

标签: c# asp.net user-controls


【解决方案1】:

当您使用您提到的 Param 属性时:

MyUserControl1.Param.Key = "Area"
MyUserControl1.Param.Value = Area 

您将收到一个错误,因为您正在访问您的 Param 属性的 get 部分。属性的 get 部分的实现总是返回 null,这将导致您的代码失败并可能出现 NullRefrenceException。

除此之外,您的控件在字典中还包含多个键值对,因此使用 Param 属性访问这些值没有意义。

尝试添加如下属性:

public IDictionary<string,string> Labels
{
    get 
    { 
       return labels; 
    }
}

然后您可以访问以下值:

myControl.Labels["Key"] = value;

【讨论】:

  • 嘿..Chiristian...非常感谢..帮助很大...它解决了我的问题...脱帽致敬..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-19
  • 1970-01-01
相关资源
最近更新 更多