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

C# 在c中为具有反射的对象添加属性#,c#,reflection,C#,Reflection,我想创建一个方法,该方法接收3个字符串作为参数,并返回一个包含三个属性的对象,它们引用了这些字符串 没有要复制的“旧对象”。应在此方法中创建属性 是用C#和反射来做这件事吗?如果是,怎么做?下面是你喜欢的,我不能做 protected Object getNewObject(String name, String phone, String email) { Object newObject = new Object(); ... //I can not add the var

我想创建一个方法,该方法接收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();
}

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


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

那么,您将如何访问这些属性?就动态访问而言,DynamicObject可能是最容易做到这一点的。我们确实需要更多的上下文。这些属性是从哪里来的?“旧物体”在哪里?为什么不好?似乎是正确的答案。这是正确的答案。通过反射添加属性不是解决方案,他以后将无法在没有反射的情况下访问这些属性。如果是这样,为什么不创建一个类呢?不妨使用
dynamic
。我没有否决你,但技术上应该是:返回新的{name=getwithreflectiontenameofsomething(),phone=GetWith…(),email=GetWith…();除非他真的想要一个名为
name
的属性以及
name
参数字符串的匿名对象。匿名类型只能在同一个方法中使用。消费这一结果是可能的,但非常尴尬(一切都通过反射)。[好的,在添加了返回动态后,似乎还可以]
 dynamic newObject = new ExpandoObject();

 newObject.name = name;
 newObject.phone = phone; 
 newObject.email = email
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));
    }