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

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

问题描述

我似乎记得读过一些关于结构如何通过 C# 在 CLR 中实现接口的文章,但我似乎找不到任何关于它的信息.不好吗?这样做会产生意想不到的后果吗?

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...

一个结构体可以实现一个接口,但存在转换、可变性和性能方面的问题.有关更多详细信息,请参阅此帖子:https://docs.microsoft.com/en-us/archive/blogs/abhinaba/c-structs-and-interface

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: https://docs.microsoft.com/en-us/archive/blogs/abhinaba/c-structs-and-interface

一般来说,结构体应该用于具有值类型语义的对象.通过在结构上实现接口,您可能会遇到装箱问题,因为结构在结构和接口之间来回转换.由于装箱,更改结构体内部状态的操作可能无法正常运行.

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天全站免登陆