将匿名类型强制转换为接口?
这似乎不可能吧?那么最好的解决方法是什么?扩展/动态?
public interface ICoOrd {
int x { get; set; }
int y { get; set; }
}
...
ICoOrd a = new {x = 44, y = 55};
参考:
This doesn't seem to be possible? So what is the best work-around? Expando / dynamic?
public interface ICoOrd {
int x { get; set; }
int y { get; set; }
}
...
ICoOrd a = new {x = 44, y = 55};
ref:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
最好的“解决方法”是创建并使用实现该接口的普通“命名”类型。
但如果您坚持使用匿名类型,请考虑使用动态接口代理框架,例如
ImpromptuInterface
。The best "workaround" is to create and use a normal, "named" type that implements the interface.
But if you insist that an anonymous type be used, consider using a dynamic interface proxy framework like
ImpromptuInterface
.不,匿名类型从不实现接口。
dynamic
也不会让您转换到接口,但会让您只访问这两个属性。请注意,匿名类型是内部
,因此如果您想使用动态
跨程序集使用它们,则需要使用InternalsVisibleTo
。No, anonymous types never implement interfaces.
dynamic
wouldn't let you cast to the interface either, but would let you just access the two properties. Note that anonymous types areinternal
, so if you want to use them across assemblies usingdynamic
, you'll need to useInternalsVisibleTo
.我知道这是一个古老的问题和答案,但我偶然发现了这一点,希望对某些单元测试做完全相同的事情。然后我想到我已经在使用 Moq (facepalm) 做类似的事情了。
我确实喜欢 ImpromptuInterface 的其他建议,但我已经在使用 Moq 了,感觉它拥有更多的追随者(这是观点而不是事实)会更稳定,支持时间更长。
所以对于这种情况,就像
编辑:只是添加另一种方式来模拟电线,开始这样做,并且更喜欢它。
I know this is an old question and answers but I stumbled on this on this looking to do exactly the same thing for some unit tests. I then occurred to me that I am already doing something like this using Moq (facepalm).
I do like the other suggestion for ImpromptuInterface but I am already using Moq and feel like it having a larger following (that is opinion and not fact) will be more stable and supported longer.
so for this case would be something like
EDIT: just adding another way to mock the cord, started doing it this way and like it a little better.