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

标签 asp.net web-user-controls

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

<uc1:mycontrol runat="server" myintarray="1,2,3" />

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

最佳答案

实现一个类型转换器,这里是一个,警告:quick&dirty,不用于生产等:

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; }
}

关于asp.net - 在 Web 用户控件中将 int 数组作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/116797/

相关文章:

asp.net - MVC 4 数据注释 "Display"属性

c# - 具有社交登录且无 MVC 依赖项的 ASP.NET WebAPI 2.2 SPA

c# - 解决错误 "The ConnectionString property has not been initialized."?

asp.net - app_themes css 文件和版本号

c# - 不同项目中的 Web 用户控件

c# - Microsoft JScript 运行时错误 : 'clientUploadComplete' is undefined

javascript - jQuery DatePicker 绑定(bind)控件不能包含在其他控件中

c# - 我的 cookie 什么时候会过期?

c# - ASP.NET 用户控件的编辑、插入、更新模式

带有内部控件的 Asp.net 用户控件