Dynamically implementing an interface in .NET 4.0 (C#)

前端 未结 5 2109
情话喂你
情话喂你 2020-12-01 02:49

With the new dynamic capabilities in .NET 4.0, it seems like it should be possible to dynamically implement an interface, e.g. given:

public interface IFoo 
         


        
5条回答
  •  自闭症患者
    2020-12-01 03:16

    The opensource framework Impromptu-Interface was designed to do this. It generates a cached lightweight proxy with a static interface and uses the dlr to forward the invocation to the original object.

    using ImpromptuInterface;
    
    public interface ISimpeleClassProps
    {
        string Prop1 { get;  }
    
        long Prop2 { get; }
    
        Guid Prop3 { get; }
    }
    

    -

    dynamic tOriginal= new ExpandoObject();
    tOriginal.Prop1 = "Test";
    tOriginal.Prop2 = 42L;
    tOriginal.Prop3 = Guid.NewGuid();
    
    ISimpeleClassProps tActsLike = Impromptu.ActLike(tOriginal);
    

提交回复
热议问题