使用TypeConverter将字符串转换为字符串数组

Dr_*_*klo 0 c# string converter

我需要转换的字符串"foo1,foo2,foo3"string[].

我想用TypeConverter它或它的孩子ArrayConverter.它的包含方法ConvertFromString.

但是,如果我调用此方法,我会遇到异常 ArrayConverter cannot convert from System.String.

我知道Split,不建议我这个解决方案.

- - 解 - -

使用@Marc Gravell的建议和@Patrick Hofman的这个主题的回答我写道 CustumTypeDescriptorProvider

public class CustumTypeDescriptorProvider:TypeDescriptionProvider
    {
        public override ICustomTypeDescriptor GetTypeDescriptor(System.Type objectType, object instance)
        {
            if (objectType.Name == "String[]") return new StringArrayDescriptor();
            return base.GetTypeDescriptor(objectType, instance);
        }
    }
public class StringArrayDescriptor : CustomTypeDescriptor
    {
        public override TypeConverter GetConverter()
        {
            return new StringArrayConverter();
        }
    }
Run Code Online (Sandbox Code Playgroud)

StringArrayConverter这篇文章下面的答案中实现了哪里.为了使用它,我添加CustumTypeDescriptorProvider了提供者集合

 TypeDescriptor.AddProvider(new CustumTypeDescriptorProvider(), typeof(string[]));
Run Code Online (Sandbox Code Playgroud)

要在它中使用它,TestClass你需要写几行:

 TypeConverter typeConverter = TypeDescriptor.GetConverter(prop.PropertyType);
 cValue = typeConverter.ConvertFromString(Value);
Run Code Online (Sandbox Code Playgroud)

我相信这可以帮助某人并使他远离愤怒的下层人士.

Pat*_*man 5

这很简单:你做不到.

new ArrayConverter().CanConvertFrom(typeof(string));
Run Code Online (Sandbox Code Playgroud)

返回false.

您最好的选择是您自己提到的选项:string.Split或者源自ArrayConverter并实现您自己的选项:

public class StringArrayConverter : ArrayConverter
{
    public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
    {
        if (sourceType == typeof(string))
        {
            return true;
        }

        return base.CanConvertFrom(context, sourceType);
    }

    public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
    {
        string s = value as string;

        if (!string.IsNullOrEmpty(s))
        {
            return ((string)value).Split(',');
        }

        return base.ConvertFrom(context, culture, value);
    }
}
Run Code Online (Sandbox Code Playgroud)

最后,我还在使用string.Split.您可以提出我们自己的实施课程.