Passing int list as a parameter to a web user control

前端 未结 8 1525
失恋的感觉
失恋的感觉 2020-12-14 04:15

I want to pass an int list (List) as a declarative property to a web user control like this:




        
相关标签:
8条回答
  • 2020-12-14 04:44

    After hooking a debugger into Cassini, I see that the null ref is actually coming from System.Web.Compilation.CodeDomUtility.GenerateExpressionForValue, which is basically trying to get an expression for the int[] array you pass into the List constructor. Since there's no type descriptor for the int[] array, it fails (and throws a null ref in the process, instead of the "can't generate property set exception" that it should).

    I can't figure out a built in way of getting a serializable value into a List<int>, so I just used a static method:

    class IntListConverter : TypeConverter {
        public static List<int> FromString(string value) {
           return new List<int>(
              value
               .Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
               .Select(s => Convert.ToInt32(s))
           );
        }
    
        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) {
            if (destinationType == typeof(InstanceDescriptor)) {
                List<int> list = (List<int>)value;
                return new InstanceDescriptor(this.GetType().GetMethod("FromString"),
                    new object[] { string.Join(",", list.Select(i => i.ToString()).ToArray()) }
                );
            }
            return base.ConvertTo(context, culture, value, destinationType);
        }
    }
    
    0 讨论(0)
  • 2020-12-14 04:51

    I solved something simular by creating 2 properties:

    public List<int> ModuleIDs { get .... set ... }
    public string ModuleIDstring { get ... set ... }
    

    The ModuleIDstring converts its value set to a list and sets the ModuleIDs property.

    This will also make the ModuleIDs usable from a PropertyGrid etc.

    Ok, not the best, typesafe solution, but for me it works.

    0 讨论(0)
提交回复
热议问题