【问题标题】:Add properties to an object with reflection in c #在 c# 中使用反射向对象添加属性
【发布时间】:2014-02-24 15:49:12
【问题描述】:

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

【问题讨论】:

  • 您将如何访问这些属性?就动态访问而言,DynamicObject 可能是您可以轻松实现的最接近的对象。不过,我们确实需要更多背景信息。
  • 这些属性是从哪里取来的? “oldObject”在哪里?

标签: c# reflection


【解决方案1】:

如果您想动态添加属性、字段等,您可以尝试使用 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

【讨论】:

    【解决方案2】:
    protected dynamic getNewObject(String name, String phone, String email)
    {
        return new { name = name, phone = phone, email = email };
    }
    

    【讨论】:

    • @Downvoter 为什么这不好?似乎是正确的答案。
    • 这是正确的答案。使用反射添加属性不是解决方案,他以后将无法在没有反射的情况下访问它们。如果是这样,为什么不创建一个类呢?不妨选择dynamic
    • 我没有对你投反对票,但从技术上讲它应该是:return new { name = GetWithReflectionTheNameOfSomething(), phone = GetWith...(), email = GetWith...() };
    • 除非他真的想要一个匿名对象,其属性名为name,并带有name 参数的字符串。
    • 匿名类型只能在同一个方法中使用。消费这个结果是可能的,但非常尴尬(一切都通过反思)。 [OK,加上return动态后好像OK了]
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-11
      • 1970-01-01
      • 2021-12-13
      • 2017-08-08
      • 2010-12-29
      相关资源
      最近更新 更多