Combine 2 classes into one class at runtime

Suppose I have a class A with some properties and attributes and a class B with the same way I can combine these 2 class properties and properties. Attributes in 1 class at runtime or better, how can I add these 2 classes to aa third class as properties of this new class with their fields, properties, methods, etc. in runtime?

Using reflection or .NET 4.0 news Dynamic or extensible object

Edit : Damn, I'm sorry that in order to not be clear, I want to create a dynamic ViewModel for MVC, where other classes are in some other assemblies, and I want them to be part of the model with Datavalidation attributes. and I don’t know how many or what exactly these classes are going to be, so I want to iterate over assemblies and select them, and then add them to the main viewing model.

+3
source share
2 answers

You cannot change the type at runtime. Expando may be an option, but I don’t understand how you want to interact with this object, since you would seem to be limited to reflection, and expando is not a huge reflection friend.

, IMO ( ) ; - Dictionary<string,object>, .

, , - partial , single, :

partial class Foo {
    private string bar;
}
partial class Foo {
    public string Bar { get {return bar;} set {bar = value;} }
}

TypeBuilder, .

+5

, ( ), , :

public class AandB
{
  private ClassA _instanceA = new ClassA();
  private ClassB _instanceB = new ClassB();

  public bool PropertyA
  {
    get
    {
      return _instanceA.PropertyA;
    }
    set
    {
      _instanceA.PropertyA = value;
    }
  }

  public bool PropertyB
  {
    get
    {
      return _instanceB.PropertyB;
    }
    set
    {
      _instanceB.PropertyB = value;
    }
  }
}
+3

Source: https://habr.com/ru/post/1756360/


All Articles