属性的对象添加在C#反射 [英] Add properties to an object with reflection in c #

查看:137
本文介绍了属性的对象添加在C#反射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个接收3个字符串作为参数的方法,并返回一个包含他们引用这些字符串的三个属性的对象。

I would like to create a method that receive 3 strings as parameter and return an object that contains three properties that they referred to these Strings.

old Object来复制。应该在此方法中创建属性。

Do not have an "old Object" to replicate. The properties should be created in this method.

是否在C#中使用反射?如果是,如何?下面是你喜欢的,我不能做。

Is to do this in C # with reflection? If so, how? Below is what you like and I am not able to do.

protected Object getNewObject(String name, String phone, String email)
{
    Object newObject = new Object();

    ... //I can not add the variables that received by the object parameter here.

    return newObject();
}


推荐答案

是这样

protected dynamic getNewObject(String name, String phone, String email)
    {


        // ... //I can not add the variables that received by the object parameter here.
        dynamic ex = new ExpandoObject();
        ex.Name = name;
        ex.Phone = phone;
        ex.Email = email;
        return ex;
    }

    private void button1_Click_2(object sender, EventArgs e)
    {
        var ye = getNewObject("1", "2", "3");
        Console.WriteLine(string.Format("Name = {0},Phone = {1},Email={2}", ye.Name, ye.Phone, ye.Email));
    }

这篇关于属性的对象添加在C#反射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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