Type Error

CSharp · Console

/Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;

public class Program
{
	public static void Main()
	{
		var simple = new HashSet<string>();
		simple.Add("1");
		simple.Add(" 1 ");
		Console.WriteLine("Simple Before => " + JsonConvert.SerializeObject(simple));
		simple = simple.DeepTrimAll();
		Console.WriteLine("Simple After => " + JsonConvert.SerializeObject(simple));
		Console.WriteLine();
		var complex = new Complex();
		complex.HS = new HashSet<string>();
		complex.HS.Add("1");
		complex.HS.Add(" 1 ");
		Console.WriteLine("Complex Before => " + JsonConvert.SerializeObject(complex));
		complex = complex.DeepTrimAll();
		Console.WriteLine("Complex After => " + JsonConvert.SerializeObject(complex));
	}
}

public class Complex
{
	public HashSet<string> HS
	{
		get;
		set;
	}
}

public static class Ext
{
	public static T DeepTrimAll<T>(this T context, Type t)where T : class
	{
		if (context is IEnumerable<string>)
		{
			var type = typeof (T);
			Console.WriteLine("T = " + type.ToString() + " , t = " + t.ToString());
			var list = new List<string>(context as IEnumerable<string>);
			for (int i = 0; i < list.Count(); i++)
			{
				list[i] = list[i].Trim();
			}

			var res = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(list), t);
			return (T)res;
		}

		var properties = typeof (T).GetProperties().Where(x => x.CanRead && x.CanWrite).ToList();
		foreach (var propertyInfo in properties)
		{
			var propType = propertyInfo.PropertyType;
			var value = propertyInfo.GetValue(context, null);
			if (propType == typeof (string))
			{
				if (!string.IsNullOrWhiteSpace(value.ToString()))
				{
					propertyInfo.SetValue(context, value.ToString().Trim());
				}
			}
			else if (!propType.IsEnum && !propType.IsPrimitive)
			{
				var newValue = value.DeepTrimAll(propType);
				propertyInfo.SetValue(context, newValue);
			}
		}

		return context;
	}

	public static T DeepTrimAll<T>(this T context)where T : class
	{
		return context.DeepTrimAll(typeof (T));
	}
}
;