在Web用户控件中将int数组作为参数传递

ern*_*ern 23 asp.net web-user-controls

我有一个int数组作为Web用户控件的属性.如果可能,我想使用以下语法设置该属性内联:

<uc1:mycontrol runat="server" myintarray="1,2,3" />
Run Code Online (Sandbox Code Playgroud)

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

mat*_*ieu 20

实现类型转换器,这里是一个,警告:快速和脏,不用于生产用途等:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

并标记控件的属性:

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


ern*_*ern 6

@mathieu,非常感谢您的代码.为了编译,我稍微修改了一下:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)


Bil*_* Jo 5

在我看来,逻辑和更可扩展的方法是从asp:列表控件中获取页面:

<uc1:mycontrol runat="server">
    <uc1:myintparam>1</uc1:myintparam>
    <uc1:myintparam>2</uc1:myintparam>
    <uc1:myintparam>3</uc1:myintparam>
</uc1:mycontrol>
Run Code Online (Sandbox Code Playgroud)