简体   繁体   English

如何在C#中扩充匿名类型对象

[英]How to augment anonymous type object in C#

I often need to augment a object with a property for instance. 我经常需要使用属性来扩充对象。 Until now (tired of it ;) and it's ugly too) I have done it this way: 直到现在(厌倦了它;)它也很丑陋)我这样做了:

var someListOfObjects = ...;

var objectsWithMyProperty = from o in someListOfObjects
                            select new
                            {
                                o.Name,    /* Just copying all the attributes I need */
                                o.Address, /* which may be all of them. */

                                SomeNewProperty = value
                            };

Is there a clever way to do this? 有一个聪明的方法来做到这一点? What I have done previously is something like this: 我以前做的是这样的:

var objectsWithMyProperty = from o in someListOfObjects
                            select new
                            {
                                OldObject = o,           /* I access all of the old properties from here */    
                                SomeNewProperty = value
                            };

I guess this could be done with some reflection, but I imagine there is a faster approach which makes something equivalent to the first cumbersome approach. 我想这可以用一些反思来完成,但我想有一种更快的方法可以使某些东西等同于第一种繁琐的方法。

Thanks, Lasse 谢谢,Lasse

No there is no support for appending new properties to an existing anonymous type. 不支持将新属性附加到现有匿名类型。 An anonymous type expression can only be used to create a brand new anonymous type with the specified properties. 匿名类型表达式只能用于创建具有指定属性的全新匿名类型。 The two best alternatives for appending new properties are the ones listed in the question. 附加新属性的两个最佳替代方案是问题中列出的方法。

I think what you are looking for is something like the ExpandoObject that was added in C# 4.0 along with the dynamic type 我认为您正在寻找的是像C#4.0中添加的ExpandoObject以及动态类型

http://msdn.microsoft.com/en-us/magazine/ff796227.aspx http://msdn.microsoft.com/en-us/magazine/ff796227.aspx

Internally it uses a dictionary so you can add/remove members dynamically. 在内部,它使用字典,因此您可以动态添加/删除成员。 The first time you try to access a property like: 您第一次尝试访问以下属性时:

obj.NewProperty = newValue

the ExpandoObject will automatically add this to its internal dictionary. ExpandoObject会自动将其添加到其内部字典中。

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM