简体   繁体   English

使用c#中的反射向对象添加属性

[英]Add properties to an object with reflection in c #

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. 我想创建一个接收3个字符串作为参数的方法,并返回一个包含三个属性的对象,这些属性引用这些字符串。

Do not have an "old Object" to replicate. 没有要复制的“旧对象”。 The properties should be created in this method. 应在此方法中创建属性。

Is to do this in C # with reflection? 是用C#做反射吗? 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();
}

If you want to add properties, fields etc. in dynamic, you may try using Expando class 如果要在动态中添加属性,字段等,可以尝试使用Expando

http://msdn.microsoft.com/en-us/library/system.dynamic.expandoobject.aspx http://msdn.microsoft.com/en-us/library/system.dynamic.expandoobject.aspx

 dynamic newObject = new ExpandoObject();

 newObject.name = name;
 newObject.phone = phone; 
 newObject.email = email
protected dynamic getNewObject(String name, String phone, String email)
{
    return new { name = name, phone = phone, email = email };
}

A complete example using Expando object is like this 使用Expando对象的完整示例是这样的

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));
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM