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

Convert string to Array of string using TypeConverter

我需要将字符串 "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();
        }
    }

其中 StringArrayConverter 在此 post 下面的答案中实现。 为了使用它,我将 CustumTypeDescriptorProvider 添加到提供者集合

 TypeDescriptor.AddProvider(new CustumTypeDescriptorProvider(), typeof(string[]));

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

 TypeConverter typeConverter = TypeDescriptor.GetConverter(prop.PropertyType);
 cValue = typeConverter.ConvertFromString(Value);

我相信这可以帮助某人并使他免于愤怒的反对者。

很简单:你做不到。

new ArrayConverter().CanConvertFrom(typeof(string));

returns 错误。

您最好的选择是您自己提到的选项: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);
    }
}

最后还是用string.Split。你当然可以想出我们自己的实现方式。

您可以使用 Regex.Matches:

string[] result =
  Regex.Matches("foo1,foo2,foo3", @",").Cast<Match>().Select(m => m.Value).ToArray();

编辑:我没弄对正则表达式,但要点仍然成立。