我不知道那篇文章的作者到底是什么意思(也许我们应该问他/她),但我想它需要的代码不止一行。关键是动态关键字(4.0 .NET 中的新关键字)允许所谓的鸭子类型。
这篇文章的作者必须编写 2 个包装类来制作FrameworkElement
和FrameworkContentElement
实现IFrameworkElement
接口。
现在有了dynamic
keywork,我们可以只写类(为了保持我们界面的舒适)。
public interface IFrameworkElement
{
/* Let's suppose we have just one property, since it is a sample */
object DataContext
{
get;
set;
}
}
public class FrameworkElementImpl : IFrameworkElement
{
private readonly dynamic target;
public FrameworkElementImpl(dynamic target)
{
this.target = target;
}
public object DataContext
{
get
{
return target.DataContext;
}
set
{
target.DataContext = value;
}
}
}
public static class DependencyObjectExtension
{
public static IFrameworkElement AsIFrameworkElement(this DependencyObject dp)
{
if (dp is FrameworkElement || dp is FrameworkContentElement)
{
return new FrameworkElementImpl(dp);
}
return null;
}
}
所以现在我们可以在我们的代码中编写如下内容:
System.Windows.Controls.Button b = new System.Windows.Controls.Button();
IFrameworkElement ife = b.AsIFrameworkElement();
ife.DataContext = "it works!";
Debug.Assert(b.DataContext == ife.DataContext);
现在,如果您不想编写包装器(或您希望的代理)类(即FrameworkElementImpl
在我们的示例中),有一些库可以为您完成(即兴接口或Castle DynamicProxy)。
您可以在这里找到一个使用 Castle DynamicProxy 的非常简单的示例:
public class Duck
{
public void Quack()
{
Console.WriteLine("Quack Quack!");
}
public void Swim()
{
Console.WriteLine("Swimming...");
}
}
public interface IQuack
{
void Quack();
}
public interface ISwimmer
{
void Swim();
}
public static class DuckTypingExtensions
{
private static readonly ProxyGenerator generator = new ProxyGenerator();
public static T As<T>(this object o)
{
return generator.CreateInterfaceProxyWithoutTarget<T>(new DuckTypingInterceptor(o));
}
}
public class DuckTypingInterceptor : IInterceptor
{
private readonly object target;
public DuckTypingInterceptor(object target)
{
this.target = target;
}
public void Intercept(IInvocation invocation)
{
var methods = target.GetType().GetMethods()
.Where(m => m.Name == invocation.Method.Name)
.Where(m => m.GetParameters().Length == invocation.Arguments.Length)
.ToList();
if (methods.Count > 1)
throw new ApplicationException(string.Format("Ambiguous method match for '{0}'", invocation.Method.Name));
if (methods.Count == 0)
throw new ApplicationException(string.Format("No method '{0}' found", invocation.Method.Name));
var method = methods[0];
if (invocation.GenericArguments != null && invocation.GenericArguments.Length > 0)
method = method.MakeGenericMethod(invocation.GenericArguments);
invocation.ReturnValue = method.Invoke(target, invocation.Arguments);
}
}
如您所见,在这种情况下,只需几行代码即可获得与作者使用相同的结果
每个元素大约 624 行 [...]