【发布时间】:2010-09-20 01:39:07
【问题描述】:
我想将一个 int 列表 (List) 作为声明性属性传递给 Web 用户控件,如下所示:
<UC:MyControl runat="server" ModuleIds="1,2,3" />
我为此创建了一个 TypeConverter:
public class IntListConverter : System.ComponentModel.TypeConverter
{
public override bool CanConvertFrom(
System.ComponentModel.ITypeDescriptorContext context,
Type sourceType)
{
if (sourceType == typeof(string)) return true;
return base.CanConvertFrom(context, sourceType);
}
public override object ConvertFrom(
System.ComponentModel.ITypeDescriptorContext context,
System.Globalization.CultureInfo culture, object value)
{
if (value is string)
{
string[] v = ((string)value).Split(
new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
List<int> list = new List<int>();
foreach (string s in vals)
{
list.Add(Convert.ToInt32(s));
}
return list
}
return base.ConvertFrom(context, culture, value);
}
public override bool CanConvertTo(ITypeDescriptorContext context,
Type destinationType)
{
if (destinationType == typeof(InstanceDescriptor)) return true;
return base.CanConvertTo(context, destinationType);
}
public override object ConvertTo(ITypeDescriptorContext context,
System.Globalization.CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(InstanceDescriptor) && value is List<int>)
{
List<int> list = (List<int>)value;
ConstructorInfo construcor = typeof(List<int>).GetConstructor(new Type[] { typeof(IEnumerable<int>) });
InstanceDescriptor id = new InstanceDescriptor(construcor, new object[] { list.ToArray() });
return id;
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
然后将属性添加到我的属性中:
[TypeConverter(typeof(IntListConverter))]
public List<int> ModuleIds
{
get { ... }; set { ... };
}
但我在运行时收到此错误:
Unable to generate code for a value of type 'System.Collections.Generic.List'1[[System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'. This error occurred while trying to generate the property value for ModuleIds.
我的问题与找到的here 类似,但解决方案没有解决我的问题:
更新:我找到了解决第一个问题的页面。我更新了上面的代码以显示我的修复。添加的代码是CanConvertTo 和ConvertTo 方法。现在我得到一个不同的错误。:
Object reference not set to an instance of an object.
这个错误似乎是由ConvertTo 方法中的某些东西间接引起的。
【问题讨论】:
-
你肯定没有在类名中写IntListConverter,在属性中写IntegerListConverter吧?
-
哈,不...我会解决的。
-
感谢您提出这个问题。我遇到了几乎同样的问题。
标签: c# asp.net typeconverter