【发布时间】:2009-12-09 23:06:52
【问题描述】:
我正在编写一个简单的包装器来“躲避”dynamic 对象对已知接口:
interface IFoo { string Bar(int fred); }
class DuckFoo : IFoo
{
private readonly dynamic duck;
public DuckFoo(dynamic duck)
{
this.duck = duck;
}
public string Bar(int fred)
{
return duck.Bar(fred);
}
}
如果dynamic 对象可以响应Bar 签名,这将正常工作。但如果它不能,只有当我调用Bar 时才会失败。我希望它可以更快地失败,即在构造 DuckFoo 包装器时进行参数验证。像这样的:
public DuckFoo(dynamic duck)
{
if(/* duck has no matching Bar method */)
throw new ArgumentException("duck", "Bad dynamic object");
this.duck = duck;
}
在 Ruby 中,有一个 respond_to? 方法可用于测试对象是否“具有”某种方法。有没有办法在 C# 4 中使用动态对象进行测试?
(我知道即使进行此检查,Bar 调用稍后也可能会失败,因为 duck 的动态特性使其稍后停止响应方法。)
【问题讨论】: