C# 将值转为类的属性值


需求

最近在做 Web Service 解析公共类,解析 SOAP 方式的 Web Service 返回的 XML,将结果直接转为指定类型

转换单个值

    static public object ChangeType(object value, Type type)
    {
        if (value == null && type.IsGenericType) return Activator.CreateInstance(type);
        if (value == null) return null;
        if (type == value.GetType()) return value;
        if (type.IsEnum)
        {
            if (value is string)
                return Enum.Parse(type, value as string);
            else
                return Enum.ToObject(type, value);
        }
        if (!type.IsInterface && type.IsGenericType)
        {
            Type innerType = type.GetGenericArguments()[0];
            object innerValue = ChangeType(value, innerType);
            return Activator.CreateInstance(type, new object[] { innerValue });
        }
        if (value is string && type == typeof(Guid)) return new Guid(value as string);
        if (value is string && type == typeof(Version)) return new Version(value as string);
        if (!(value is IConvertible)) return value;
        return Convert.ChangeType(value, type);
    }

直接转为特定类型实例

class Program
{
    static void Main(string[] args)
    {
        Dictionary<string, string> dict = new Dictionary<string, string>();
        dict.Add("Id", Guid.NewGuid().ToString());
        dict.Add("FirstName", "Lance");
        dict.Add("LastName", "Chang");
        dict.Add("Birthday", "1991-02-09");
        dict.Add("Career", "3.5");
        dict.Add("Version", new Version(2, 9, 2016).ToString());
        dict.Add("Gender", "1");

        var iter = Assign<ITer>(dict);
        if (iter != null)
        {
            iter.GetType().GetProperties().ToList().ForEach(_ =>
            {
                Console.WriteLine(_.Name + ":" + _.GetValue(iter, null));
            });
        }

        Console.ReadKey(true);
    }

    /// <summary>
    /// 为指定对象分配参数
    /// </summary>
    /// <typeparam name="T">待赋值的类型</typeparam>
    /// <param name="dic">字段/值</param>
    /// <returns></returns>
    static T Assign<T>(Dictionary<string, string> dic) where T : new()
    {

        try
        {
            Type t = typeof(T);
            T entity = (T)Activator.CreateInstance(t);// new T();

            var fields = t.GetProperties();

            string val = string.Empty;
            object obj = null;
            foreach (var field in fields)
            {
                if (!dic.Keys.Contains(field.Name))
                    continue;
                val = dic[field.Name];
                //是否可以转换
                if (!(val is IConvertible))
                    obj = val;
                //枚举类型
                else if (field.PropertyType.IsEnum)
                {
                    if (val is string)
                        obj = Enum.Parse(field.PropertyType, val as string);
                    else
                        obj = Enum.ToObject(field.PropertyType, val);
                }
                //GUID 类型
                else if (field.PropertyType == typeof(Guid))
                    obj = Guid.Parse(val);
                //Version类型
                else if (field.PropertyType == typeof(Version))
                    obj = new Version(val);
                //非泛型
                else if (!field.PropertyType.IsGenericType)
                    obj = string.IsNullOrEmpty(val) ? null : Convert.ChangeType(val, field.PropertyType);
                else //泛型Nullable<>
                {
                    Type genericTypeDefinition = field.PropertyType.GetGenericTypeDefinition();
                    if (genericTypeDefinition == typeof(Nullable<>))
                    {
                        obj = string.IsNullOrEmpty(val)
                          ? null
                          : Convert.ChangeType(val, Nullable.GetUnderlyingType(field.PropertyType));
                    }
                    else
                    {
                        Type innerType = field.PropertyType.GetGenericArguments()[0];
                        object innerValue = ChangeType(val, innerType);
                        obj = Activator.CreateInstance(field.PropertyType, new object[] { innerValue });
                    }
                }
                field.SetValue(entity, obj, null);
            }

            return entity;
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        return default(T);

    }
}

class ITer
{
    public Guid Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime Birthday { get; set; }
    public decimal Career22 { get; set; }
    public Nullable<decimal> Career { get; set; }
    public Version Version { get; set; }
    public Gender Gender { get; set; }
}

enum Gender
{
    Female,
    Male
}

知识共享许可协议
《C# 将值转为类的属性值》 常伟华 创作。
本作品采用知识共享署名-相同方式共享 4.0 国际许可协议 | 3.0 中国大陆许可协议进行许可。

站内公告