C# 将object对象转换为实体对象

2021-06-10 14:03

阅读:644

标签:年龄   new   ==   usermod   ble   public   string   创建   转换   

C# 将object对象转换为实体对象.代码如下:

/// 
/// 将object对象转换为实体对象
/// 
/// 实体对象类名
/// object对象
/// 
private T ConvertObject(object asObject) where T : new()
{
    //创建实体对象实例
    var t = Activator.CreateInstance();
    if (asObject != null)
    {
        Type type = asObject.GetType();
        //遍历实体对象属性
        foreach (var info in typeof(T).GetProperties())
        {
            object obj = null;
            //取得object对象中此属性的值
            var val = type.GetProperty(info.Name)?.GetValue(asObject
            if (val != null)
            {
                //非泛型
                if (!info.PropertyType.IsGenericType)
                    obj = Convert.ChangeType(val, info.PropertyType)
                else//泛型Nullable
                {
                    Type genericTypeDefinition = info.PropertyType.GetGenericTypeDefinition();
                    if (genericTypeDefinition == typeof(Nullable))
                    {
                        obj = Convert.ChangeType(val, Nullable.GetUnderlyingType(info.PropertyType));
                    }
                }
                info.SetValue(t, obj, null);
            }
        }
    }
    return t;
}

调用时:

/// 
/// test
/// 
public void test()
{
    var obj = new {
        id=1,name="张三",sex=1,age=22
    };
    //转换
    var userModel = ConvertObject(obj);
}

/// 
/// 用户
/// 
public class user
{
    /// 
    /// 编号
    /// 
    public int id { set; get; }
    /// 
    /// 姓名
    /// 
    public string name { set; get; }
    /// 
    /// 性别
    /// 
    public int sex { set; get; }
    /// 
    /// 年龄
    /// 
    public int age { set; get; }
}

是不是很简单?

C# 将object对象转换为实体对象

标签:年龄   new   ==   usermod   ble   public   string   创建   转换   

原文地址:https://www.cnblogs.com/aoede-jacqueline/p/10599257.html


评论


亲,登录后才可以留言!