当前位置: 移动技术网 > IT编程>开发语言>.net > C# 将object对象转换为实体对象

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

2019年03月27日  | 移动技术网IT编程  | 我要评论

大飞机c919最新消息,超速战警,边寨匪事

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

/// <summary>
/// 将object对象转换为实体对象
/// </summary>
/// <typeparam name="t">实体对象类名</typeparam>
/// <param name="asobject">object对象</param>
/// <returns></returns>
private t convertobject<t>(object asobject) where t : new()
{
    //创建实体对象实例
    var t = activator.createinstance<t>();
    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;
}

调用时:

/// <summary>
/// test
/// </summary>
public void test()
{
    var obj = new {
        id=1,name="张三",sex=1,age=22
    };
    //转换
    var usermodel = convertobject<user>(obj);
}

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

是不是很简单?

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网