它是安全的结构实现接口? [英] Is it safe for structs to implement interfaces?

查看:94
本文介绍了它是安全的结构实现接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎记得阅读关于它是如何坏的东西结构实现接口在通过C#CLR,但我似乎无法找到任何关于它。它是坏?是否有意想不到的这样做的后果是什么?

 公共接口美孚{酒吧GetBar(); }
公共结构FUBAR:美孚{公共酒吧GetBar(){返回新酒吧(); }}


解决方案

有几件事情在这个问题上怎么回事...

这是可能的结构来实现一个接口,但也有大约来与铸造,可变性和性能问题。看到这个帖子了解更多详情:<一href=\"http://blogs.msdn.com/abhinaba/archive/2005/10/05/477238.aspx\">http://blogs.msdn.com/abhinaba/archive/2005/10/05/477238.aspx

在一般情况下,结构应用于具有值类型语义对象。通过在一个结构实现接口的结构是结构和接口之间进行转换来回可以运行成拳的担忧。由于拳击的结果,改变结构的内部状态操作可能无法正常运行。

I seem to remember reading something about how it is bad for structs to implement interfaces in CLR via C#, but I can't seem to find anything about it. Is it bad? Are there unintended consequences of doing so?

public interface Foo { Bar GetBar(); }
public struct Fubar : Foo { public Bar GetBar() { return new Bar(); } }

解决方案

There are several things going on in this question...

It is possible for a struct to implement an interface, but there are concerns that come about with casting, mutability, and performance. See this post for more details: http://blogs.msdn.com/abhinaba/archive/2005/10/05/477238.aspx

In general, structs should be used for objects that have value-type semantics. By implementing an interface on a struct you can run into boxing concerns as the struct is cast back and forth between the struct and the interface. As a result of the boxing, operations that change the internal state of the struct may not behave properly.

这篇关于它是安全的结构实现接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆