如何为枚举列表创建InstanceDescriptor?

Nit*_*ant 6 c# asp.net custom-controls typeconverter typedescriptor

类似的问题:将int list作为参数传递给Web用户控件
是否有类似enum类型的示例?

我正在创建一个asp.net自定义控件,我想在其中将逗号分隔的枚举列表作为属性传递.
我正在写一个TypeConverter用于将逗号分隔的字符串值转换为枚举列表.

ConvertTo方法中,
如何为InstanceDescriptor枚举列表创建对象?

我目前的代码如下:

//enum
public enum MyEnum {Hello, World}

//main method
List<MyEnum> list = new List<MyEnum>();
list.Add(MyEnum.Hello);
list.Add(MyEnum.World);
ConstructorInfo constructor = typeof(List<MyEnum>).GetConstructor( Type.EmptyTypes );
InstanceDescriptor idesc = new InstanceDescriptor(constructor, list);
Run Code Online (Sandbox Code Playgroud)

这与消息失败

Length mismatch
Run Code Online (Sandbox Code Playgroud)

我想知道为什么

Mic*_*Liu 2

发生“长度不匹配”错误是因为您检索了默认List<T>构造函数,该构造函数具有零个参数,然后您要求使用两个参数InstanceDescriptor调用该构造函数,并且。MyEnum.HelloMyEnum.World

您可能认为可以使用接受单个参数的备用List<T>构造函数IEnumerable<T>

ConstructorInfo constructor =
    typeof(List<MyEnum>).GetConstructor(new[] { typeof(IEnumerable<MyEnum>) });
InstanceDescriptor idesc = new InstanceDescriptor(constructor, new[] { list });
Run Code Online (Sandbox Code Playgroud)

这让人InstanceDescriptor高兴,但不幸的是,您会发现 ASP.NET 现在会抛出异常(与您链接到的问题NullReferenceException相同),因为 ASP.NET 不知道如何处理参数。IEnumerable<T>

这里有两种方法来解决这个问题。

解决方案 1:更改自定义控件和类型转换器以MyEnum[]使用List<MyEnum>. 这是可行的,因为 ASP.NET 可以处理数组。

解决方案 2:List<MyEnum>创建一个从数组创建 a 的静态帮助器方法:

public static List<MyEnum> ToList(MyEnum[] values)
{
    return new List<MyEnum>(values);
}
Run Code Online (Sandbox Code Playgroud)

然后更改类型转换器以创建一个InstanceDescriptor调用帮助器方法的类型转换器,并将列表作为数组传递给它:

MethodInfo method = typeof(MyEnumListConverter).GetMethod("ToList");
InstanceDescriptor idesc = new InstanceDescriptor(method, new[] { list.ToArray() });
Run Code Online (Sandbox Code Playgroud)