mercredi 27 avril 2016

Converting value type array to reference type array

I need to write an exception class that takes a message and an info object of any type (usually anonymous object).

I have the following code:

public SpecialException(string message, object info) : this(message)
{
    StringBuilder sb = new StringBuilder();
    foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(info.GetType()))
    {
        object value = property.GetValue(info);
        string valueStr = value.GetType().IsArray ? (value as IEnumerable<object>).Select(x => x.ToString()).Aggregate((x, y) => $"{x}, {y}") : value.ToString();
        sb.AppendLine($"{property.Name} = {valueStr}");
    }
    Info = sb.ToString();
}

The problem is, this code does not work when one of the anonymous object's properties is an array of value-typed items since they do not inherit object and this type of covariance cannot work with them.

What I tried, but found either not to work or inelegant:

  • Using a Dictionary<string, object> - Cannot override the Add method
  • Using the IDictionary<string, object> interface - Do not want to implement all of the interface's methods for a simple exception
  • Using an ExpandoObject and dynamic keyword - Will run into the same problems as the code above
  • Serializing to JSON using dynamic and Newtonsoft JSON - Do not want a dependancy on a third-party library (or the Web DLL)

I assume there is an elegant way (probably using reflection) to achieve this, perhaps by somehow iterating through the array. Can anyone suggest a solution?





Aucun commentaire:

Enregistrer un commentaire