Passing int list as a parameter to a web user control

前端 未结 8 1538
失恋的感觉
失恋的感觉 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, so I just used a static method:

    class IntListConverter : TypeConverter {
        public static List FromString(string value) {
           return new List(
              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 list = (List)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);
        }
    }
    

提交回复
热议问题