简体   繁体   English

使用反射/类型转换将C#数组转换为字符串

[英]Convert C# Array to String Using Reflection / Type Conversion

I am trying to figure out how to convert an arbitrary array or collection to a string via reflection and it's driving me nuts..NUTS...I'm about yay close to putting my red swingline through the computer monitor here. 我试图弄清楚如何通过反射将任意数组或集合转换为字符串,这使我发疯..NUTS ...我差不多要把红色的摆动线穿过这里的计算机监视器。

So for example, given an array of Color objects, I want the default string representation of that array (you know, semicolon-delimited or whatever) using an ArrayConverter or ColorConverter or whatever the appropriate converter is. 因此,例如,给定一个Color对象数组,我想要使用ArrayConverter或ColorConverter或任何适当的转换器来作为该数组的默认字符串表示形式(用分号分隔或其他内容)。 I can do this for simple object types but collections elude me. 我可以为简单的对象类型执行此操作,但是集合使我难以理解。

Here's how I'm iterating the properties of an (arbitrary) object using reflection. 这是我使用反射迭代(任意)对象的属性的方式。 How do I generically convert an array containing arbitrary types to a standard string representation using the appropriate converter? 如何使用适当的转换器将包含任意类型的数组一般转换为标准字符串表示形式?

Type t = widget.GetType();

System.Reflection.PropertyInfo[] props = t.GetProperties();
foreach (PropertyInfo prop in props)
{
    TypeConverter converter = TypeDescriptor.GetConverter(prop.PropertyType);
    if (converter != null)
    {
        object o = prop.GetValue(widget, null);
        att.Value = converter.ConvertToString(o);
        // This returns some BS like "System.Array [2]"
        // I need the actual data.
    }
}

EDIT: If I try this: 编辑:如果我尝试这样做:

att.Value = o.ToString();

It returns: "System.Drawing.Color[]". 它返回:“ System.Drawing.Color []”。 Whereas I want "255,202,101;127,127,127" or whatever the default string representation is used in for example a property editor. 而我想要“ 255,202,101; 127,127,127”或任何在属性编辑器中使用的默认字符串表示形式。

Thanks! 谢谢!

There's no such thing as "standard string representation of an array". 没有“数组的标准字符串表示形式”之类的东西。 But you can always: 但您始终可以:

string stringRepresentation = 
    string.Join(",",
        Array.Convert<Foo, string>(delegate(Foo f) { return f.ToString(); }));

Just calling ToString() on individual members together should work... 仅在单个成员上一起调用ToString()应该可以工作...

object[] data = GetData();
string convertedData = String.Join(",",(from item in data select item.ToString()).ToArray());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM