在c#中为具有反射的对象添加属性

本文关键字:反射的 对象 添加 属性 | 更新日期: 2023-09-27 18:28:06

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

没有要复制的"旧对象"。应使用此方法创建属性。

是在C#中用反射来做这件事吗?如果是,如何?下面是你喜欢的,我不能做。

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

在c#中为具有反射的对象添加属性

如果您想在动态中添加属性、字段等,您可以尝试使用Expando

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

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