6

我有类方法:

public object MyMethod(object obj)
{
   // I want to add some new properties example "AddedProperty = true"
   // What must be here?
   // ...

   return extendedObject;
}

和:

var extendedObject = this.MyMethod( new {
   FirstProperty = "abcd",
   SecondProperty = 100 
});

现在extendedObject 有了新的属性。请帮忙。

4

3 回答 3

13

你不能那样做。

如果您想要一个可以在运行时添加成员的动态类型,那么您可以使用ExpandoObject.

表示一个对象,其成员可以在运行时动态添加和删除。

这需要 .NET 4.0 或更高版本。

于 2010-12-21T19:59:59.643 回答
1

您可以使用 Dictionary (property, value),或者如果您使用的是 c# 4.0,您可以使用新的动态对象 (ExpandoObject)。

http://msdn.microsoft.com/en-us/library/dd264736.aspx

于 2010-12-21T20:00:57.663 回答
1

您在编译时知道属性的名称吗?因为你可以这样做:

public static T CastByExample<T>(object o, T example) {
    return (T)o;
}

public static object MyMethod(object obj) {
    var example = new { FirstProperty = "abcd", SecondProperty = 100 };
    var casted = CastByExample(obj, example);

    return new {
        FirstProperty = casted.FirstProperty,
        SecondProperty = casted.SecondProperty,
        AddedProperty = true
    };
}

然后:

var extendedObject = MyMethod(
    new {
        FirstProperty = "abcd",
        SecondProperty = 100
    }
);

var casted = CastByExample(
    extendedObject,
    new {
        FirstProperty = "abcd",
        SecondProperty = 100,
        AddedProperty = true 
    }
);
Console.WriteLine(xyz.AddedProperty);

请注意,这在很大程度上依赖于这样一个事实,即同一程序集中的两个匿名类型具有相同名称、相同类型、相同顺序的相同类型的属性。

但是,如果你要这样做,为什么不直接创建具体类型呢?

输出:

True
于 2010-12-21T20:05:57.130 回答