C# 动态扩展对象
是否可以扩展现有对象?
我有代码
var record = new
{
id,
name
};
和匿名对象列表,
var list = new List<object>(){ object1, object2 };
我可以稍后将它们添加到对象中吗? 就像这样
foreach (var o in list)
{
record.add(o);
}
我会得到这个结果
var record = new
{
id,
name,
object1,
object2
};
is it possible to extends a existing object ?
i have the code
var record = new
{
id,
name
};
and have a list of anonymous objects
var list = new List<object>(){ object1, object2 };
Can i add them later to the object ?
Like something as
foreach (var o in list)
{
record.add(o);
}
that i will get this as result
var record = new
{
id,
name,
object1,
object2
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
简而言之,不。至少,匿名类型不行。这里有两种方法;
dynamic
可能会给你你想要的东西,但组合起来很麻烦。除此之外,一个基本的属性包 - 甚至简单的Dictionary
就可以了。唯一的区别是:问题
然而,在尝试一步将列表(每个列表基本上都是匿名的)与属性结合起来时,存在一个更根本的 。您可以执行此操作通过自定义属性模型进行数据绑定,但这......很棘手。
In short, no. At least, not with anonymous types. There are two approaches here;
dynamic
might give you what you want, but is fiddly for combining. Other than that, a basic property bag - even simplyDictionary<string,object>
would do. The only difference being that:becomes
There is a more fundamental problem, though, in trying to combine a list (each of which is largely anonymous) with properties in a single step. You can do this for data-binding purpose via custom property models, but it is... tricky.
您可以做的是创建一个类扩展。不可能在运行时添加新方法,但你可以这样做:
如果你想扩展这个类的行为,你可以编写一个扩展类。像这样:
这样您就可以从 OneClass 对象调用此扩展方法:
有一些规则需要遵循:
What you can do is create a class Extension. It is not possible to add new methods in the runtime, but you can do something like this:
if you want to extend this class behavior, you can write an extension class. Like this:
This way you can call this extension method from your OneClass objects:
There are some rules to follow:
如果将来有人遇到这个问题,我最近发布了一个库来做到这一点。您可以在 nuget.org 上找到它 - 它被称为(毫不奇怪)ObjectExtend。
您可以通过从 Nuget 获取它或通过您最喜欢的包管理器来安装它。您还可以查看源代码,简介,或详细概述其工作原理。
简短的版本是 - 安装软件包,确保使用
using Rophuine.LINQPad.ObjectExtend;
导入命名空间,现在您应该能够在您的设备上调用.Extend
对象。需要注意的是:这是探索性编码的一项很好的技术,但我建议不要将其用于任何将要维护或投入生产的内容。
In case anyone runs into this question in the future, I have recently published a library to do exactly this. You can find it on nuget.org - it's called (unsurprisingly) ObjectExtend.
You can install it by grabbing it from Nuget or via your favourite package manager. You can also check out the source code, a brief introduction, or a detailed overview of how it works.
The short version is - install the package, make sure you import the namespace with
using Rophuine.LINQPad.ObjectExtend;
, and now you should be able to call.Extend
on your objects.A caveat: this is a great technique for exploratory coding, but I recommend against it for anything which will be maintained or go to production.
从 .net4 开始,您可以使用 ExpandoObject 来做类似的事情。
例如:
Since .net4 you could use ExpandoObject to do stuff like that.
For example: