将类转换为动态并添加属性 [英] Convert class to dynamic and add properties

查看:84
本文介绍了将类转换为动态并添加属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个课程 MyClass 。我想将其转换为动态对象,以便添加属性。

I have a class MyClass. I would like to convert this to a dynamic object so I can add a property.

这就是我所希望的:

dynamic dto = Factory.Create(id);
dto.newProperty = "123";

我收到错误:

WEB.Models.MyClass does not contain a definition for 'newProperty'

这不可能吗?

推荐答案

以下内容对我有用:


它允许您将任何对象转换为Expando对象。

The following has worked for me in the past:
It allows you to convert any object to an Expando object.

public static dynamic ToDynamic<T>(this T obj)
{
    IDictionary<string, object> expando = new ExpandoObject();

    foreach (var propertyInfo in typeof(T).GetProperties())
    {
        var currentValue = propertyInfo.GetValue(obj);
        expando.Add(propertyInfo.Name, currentValue);
    }
    return expando as ExpandoObject;
}

基于: http://geekswithblogs.net/Nettuce/archive/2012/ 06/02 /将动态转换为类型并将转换为动态.aspx

这篇关于将类转换为动态并添加属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆