net4.0/netstd2.0框架允许您使用静态接口包装任何对象(静态或动态),即使它没有从它继承。它通过在代理中发出缓存的动态绑定代码来实现此目的。本文主要介绍在代码中没有继承的接口,使用使用ImpromptuInterface动态实现继承的方法代码。

1、ImpromptuInterface的安装引用

通过Nuget引用,使用Nuget图形管理器=》搜索"ImpromptuInterface"=》找到然后点击"安装"。

相关文档VS(Visual Studio)中Nuget的使用

2、使用示例代码

using ImpromptuInterface;
    using Dynamitey;
    public interface IMyInterface{
       string Prop1 { get;  }
        long Prop2 { get; }
        Guid Prop3 { get; }
        bool Meth1(int x);
   }
   //Anonymous Class
    var anon = new {
             Prop1 = "Test",
             Prop2 = 42L,
             Prop3 = Guid.NewGuid(),
             Meth1 = Return<bool>.Arguments<int>(it => it > 5)
    }
    var myInterface = anon.ActLike<IMyInterface>();

 //Dynamic Expando object
dynamic expando = new ExpandoObject();
expando.Prop1 ="Test";
expando.Prop2 = 42L;
expando.Prop3 = Guid.NewGuid();
expando.Meth1 = Return<bool>.Arguments<int>(it => it > 5);
IMyInterface myInterface = Impromptu.ActLike(expando);

官方地址https://github.com/ekonbenefits/impromptu-interface


推荐文档