vendredi 25 octobre 2019

Does C# have an easy way to create a "shadow" type?

Given an object that might be something like

[TypeIdentifier("foo")]
public class Foo
{
    public string Thingy { get; }

    public int Blah { get; }

    pulic Foo(Thingy thingy, Blah blah)
    {
        this.Thingy = thingy ?? throw new ArgumentNullException(thingy);
        this.Blah = blah ?? throw new ArgumentNullException(blah);
    }
}

I want at runtime to generate a type like

public class FooShadow_ec3dddf4
{
    public string Thingy { get; }

    public int Blah { get; }

    public string TypeId { get => "foo"; }

    pulic FooShadow_ec3dddf4(Thingy thingy, Blah blah)
    {
        this.Thingy = thingy ?? throw new ArgumentNullException(thingy);
        this.Blah = blah ?? throw new ArgumentNullException(blah);
    }
}

and in fact generate an instance of that type with the same property values for Thingy and Blah.

Impl:

public static object CreateTypedShadow(this object obj)
{
   // ... 
} 

Usage:

var shadow = obj.CreateTypedShadow();

I know this possible using features such as TypeBuilder but is quite complicated so I'm wondering whether there is a shortcut for this exact scenario.





Aucun commentaire:

Enregistrer un commentaire