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

本文关键字:字符串 数组 转换 使用 TypeConverter | 更新日期: 2023-09-27 18:27:05

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

我想使用TypeConverter或其子ArrayConverter。其包含方法CCD_ 5。

但是如果我调用这个方法,我会捕获一个异常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();
        }
    }

其中CCD_ 9在本文下面的回答中实现。为了使用它,我将CustumTypeDescriptorProvider添加到供应商的集合中

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

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

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

我相信这可以帮助某人,使他免于愤怒的悲观情绪。

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

很简单:你不能。

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

返回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);
    }
}

最后,我仍然使用string.Split。当然,您可以提出我们自己的实施方案。

您可以使用Regex.Matches:

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

编辑:我没有得到正确的正则表达式,但要点仍然存在。