2010-12-21 36 views
2

的對象我有類方法:如何延長匿名類

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有新的屬性。請幫助。

+0

,你爲什麼和匿名類這樣做呢? – jason 2010-12-21 20:00:34

+0

我正在使用ASP.NET MVC,我希望任何JSON數據都可以用我的調試信息進行擴展。 – 2010-12-21 20:05:36

回答

9

你不能那樣做。

如果您想要在運行時添加成員的動態類型,那麼您可以使用ExpandoObject

表示一個對象,其成員可以在運行時動態添加和刪除。

這需要.NET 4.0或更新版本。

+0

謝謝,我會試試看。 – 2010-12-21 20:10:10

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