C# 动态扩展对象

发布于 2024-10-12 15:12:03 字数 407 浏览 3 评论 0原文

是否可以扩展现有对象?

我有代码

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

﹉夏雨初晴づ 2024-10-19 15:12:03

简而言之,不。至少,匿名类型不行。这里有两种方法; dynamic 可能会给你你想要的东西,但组合起来很麻烦。除此之外,一个基本的属性包 - 甚至简单的 Dictionary 就可以了。唯一的区别是:

obj.id

问题

obj["id"]

然而,在尝试一步将列表(每个列表基本上都是匿名的)与属性结合起来时,存在一个更根本的 。您可以执行此操作通过自定义属性模型进行数据绑定,但这......很棘手。

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 simply Dictionary<string,object> would do. The only difference being that:

obj.id

becomes

obj["id"]

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.

山色无中 2024-10-19 15:12:03

您可以做的是创建一个类扩展。不可能在运行时添加新方法,但你可以这样做:

public class OneClass
{
  private List<object> items;
  public List<object> Items { get { return items; } }
  public void AddOne(object item)
  {
    items.Add(item);
  }
}

如果你想扩展这个类的行为,你可以编写一个扩展类。像这样:

public static class OneClassExtensions
{
  public void AddMany(this OneClass self, params object[] items)
  {
    foreach(object item in items)
    {
      self.Items.Add(item);
    }
  }
}

这样您就可以从 OneClass 对象调用此扩展方法:

OneClass obj = new OneClass();
obj.AddOne("hello");
obj.AddMany("Hello", "world"); // Extension method

有一些规则需要遵循:

  1. 扩展类必须具有“static”修饰符,
  2. 您需要在第一个参数之前放置“this”前缀。这个参数就是对象本身。
  3. 为了在代码中使用此扩展类,您必须使用包含该扩展类的命名空间,例如在每个要使用扩展方法的 .cs 文件中使用“using Some.Namespace.That.Has.An.Extension”。

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:

public class OneClass
{
  private List<object> items;
  public List<object> Items { get { return items; } }
  public void AddOne(object item)
  {
    items.Add(item);
  }
}

if you want to extend this class behavior, you can write an extension class. Like this:

public static class OneClassExtensions
{
  public void AddMany(this OneClass self, params object[] items)
  {
    foreach(object item in items)
    {
      self.Items.Add(item);
    }
  }
}

This way you can call this extension method from your OneClass objects:

OneClass obj = new OneClass();
obj.AddOne("hello");
obj.AddMany("Hello", "world"); // Extension method

There are some rules to follow:

  1. The extension class must have the `static' modifier
  2. you need to put the `this' prefix before the first argument. This argument would be the object itself.
  3. In order to use this extension class in your code, you must use the namespace that contains that extension class, like `using Some.Namespace.That.Has.An.Extension' in every .cs file where you want to use extension methods.
宁愿没拥抱 2024-10-19 15:12:03

如果将来有人遇到这个问题,我最近发布了一个库来做到这一点。您可以在 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.

笑梦风尘 2024-10-19 15:12:03

从 .net4 开始,您可以使用 ExpandoObject 来做类似的事情。

例如:

        var objs = new List<ExpandoObject>();

        for (var i = 0; i < 10; i++)
        {
            dynamic eObj = new ExpandoObject();
            eObj.Property = i;
            objs.Add(eObj);
        }

        foreach (dynamic obj in objs)
        {
            obj.Property2 = "bubuValue" + obj.Property;
            obj.Property3 = "bubuValue" + obj.Property2;
        }

        foreach (dynamic obj in objs)
        {
            Console.WriteLine(obj.Property3);
        }

Since .net4 you could use ExpandoObject to do stuff like that.

For example:

        var objs = new List<ExpandoObject>();

        for (var i = 0; i < 10; i++)
        {
            dynamic eObj = new ExpandoObject();
            eObj.Property = i;
            objs.Add(eObj);
        }

        foreach (dynamic obj in objs)
        {
            obj.Property2 = "bubuValue" + obj.Property;
            obj.Property3 = "bubuValue" + obj.Property2;
        }

        foreach (dynamic obj in objs)
        {
            Console.WriteLine(obj.Property3);
        }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文