加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net – 在web用户控件中传递int数组作为参数

发布时间:2020-12-15 18:47:16 所属栏目:asp.Net 来源:网络整理
导读:我有一个int数组作为Web用户控件的属性。如果可能,我想使用以下语法内联设置该属性: uc1:mycontrol runat="server" myintarray="1,2,3" / 这将在运行时失败,因为它会期待一个实际的int数组,而是传递一个字符串。我可以使myintarray一个字符串,并在sette
我有一个int数组作为Web用户控件的属性。如果可能,我想使用以下语法内联设置该属性:
<uc1:mycontrol runat="server" myintarray="1,2,3" />

这将在运行时失败,因为它会期待一个实际的int数组,而是传递一个字符串。我可以使myintarray一个字符串,并在setter中解析,但我想知道是否有一个更优雅的解决方案。

解决方法

实施类型转换器,这里是一个,警告:快速和脏,不用于生产使用等:
public class IntArrayConverter : System.ComponentModel.TypeConverter
{
    public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context,Type sourceType)
    {
        return sourceType == typeof(string);
    }
    public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context,System.Globalization.CultureInfo culture,object value)
    {
        string val = value as string;
        string[] vals = val.Split(',');
        System.Collections.Generic.List<int> ints = new System.Collections.Generic.List<int>();
        foreach (string s in vals)
            ints.Add(Convert.ToInt32(s));
        return ints.ToArray();
    }
}

并标记您的控件的属性:

private int[] ints;
[TypeConverter(typeof(IntsConverter))]
public int[] Ints
{
    get { return this.ints; }
    set { this.ints = value; }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读