简体   繁体   中英

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.

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. 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[]". Whereas I want "255,202,101;127,127,127" or whatever the default string representation is used in for example a property editor.

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...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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