Gre*_*ech 46 .net c# dynamic .net-4.0 c#-4.0
借助.NET 4.0中的新动态功能,似乎应该可以动态实现接口,例如:
public interface IFoo
{
string Bar(int baz);
}
public class Foo : IFoo
{
public string Bar(int baz) { return baz.ToString(); }
}
public class Proxy : IDynamicMetaObjectProvider
{
private readonly object target;
public Proxy(object target) { this.target = target; }
// something clever goes here
}
Run Code Online (Sandbox Code Playgroud)
然后我希望有一些方法可以写:
dynamic proxy = new Proxy(new Foo());
IFoo fooProxy = (IFoo)proxy; // because the target object implements it
string bar = fooProxy.Bar(123); // delegates through to the target implementation
Run Code Online (Sandbox Code Playgroud)
但是,到目前为止,我还不确定要替换什么// something clever goes here.
所以,我的问题是:
这实际上可以用动态运行时吗?似乎动态实现方法和属性之类的东西相当容易,但我没有找到任何关于动态实现接口和转换的文档.
假设这是可能的,它有多难?(你可以假设我是一个体面的程序员,拥有丰富的反思经验,但对动态框架不熟悉.)
是否有任何资源可以帮助我指出正确的方向来实现这样的事情?或者甚至已经完成这种事情的样本我可以用作起点?
jbt*_*ule 44
开源框架Impromptu-Interface旨在实现这一目标.它使用静态接口生成缓存的轻量级代理,并使用dlr将调用转发到原始对象.
using ImpromptuInterface;
public interface ISimpeleClassProps
{
string Prop1 { get; }
long Prop2 { get; }
Guid Prop3 { get; }
}
Run Code Online (Sandbox Code Playgroud)
-
dynamic tOriginal= new ExpandoObject();
tOriginal.Prop1 = "Test";
tOriginal.Prop2 = 42L;
tOriginal.Prop3 = Guid.NewGuid();
ISimpeleClassProps tActsLike = Impromptu.ActLike(tOriginal);
Run Code Online (Sandbox Code Playgroud)
Nic*_*oiu 14
据我所知,如果没有手动干预,编写或生成将接口成员转发到包装实例的代码是不可能的.如果您希望看到Microsoft提供的此类支持,您可以考虑通过https://connect.microsoft.com/VisualStudio/feedback/details/526307/add-automatic-generation-of-interface进行投票.-implementation-via-implementation-member .