C# 动态类

标签 c#

我正在谈论类似于动态的东西。 This没有回答我的问题,所以才有这个问题。我想要一个可以在运行时添加属性的类。它需要从object类型继承。

我见过从 DynamicObject 继承,但它没有说明如何在运行时添加属性。请帮我解释一下这个问题吗?

我有一堂这样的课:

public class SomeModel : DynamicObject {
       public string SomeMandatoryProperty {get; set;}
}

我想在运行时将另一个类的所有属性添加到此类。例如。

SomeModel m = new SomeModel();
m = someOtherClass;
string hi = m.otherClassProp; //Property from other class is added.
string mandatory = m.SomeMandatoryProperty; //From the mandatory property set previously.

最佳答案

我认为您正在寻找 ExpandoObject :

The ExpandoObject class enables you to add and delete members of its instances at run time and also to set and get values of these members. This class supports dynamic binding, which enables you to use standard syntax like sampleObject.sampleMember instead of more complex syntax like sampleObject.GetAttribute("sampleMember").

dynamic manager;

manager = new ExpandoObject();
manager.Name = "Allison Brown";
manager.Age = 42;
manager.TeamSize = 10;

关于C# 动态类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5293877/

相关文章:

c# - 从下拉列表中获取 IEnumerable<T> 的选定值

C# WebClient,仅支持HTML3.2

c# - 如何使用 EWL 将自定义样式表添加到 Web 应用程序?

c# - 如何为每个 xUnit.net 测试方法使用单独的 AppDomain?

c# - 如何忽略 asmx 的 JSON 响应中的空值

c# - 代码分析 c# .NET CA1822

c# - 无法在 LINQ to Entities 查询中构造实体

c# - 用于精确匹配 N 数的正则表达式

c# - 本地化与文字之间的区别

c# - 返回继承类类型列表的基类中的函数