在Struct中存储引用类型 [英] Storing reference types in Struct

查看:54
本文介绍了在Struct中存储引用类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我在C#中有一个非常简单的结构

Say I had a very simple struct in c#

   public struct foo{
   public  int a{get;set;}
   public  int b{get;set;}
   public  int c{get;set;}
   public  int d{get;set;}
   public  string hello {get;set;}
   }

我认为上面的内容比使用 class 更为有效"吗?

I take it the above is more 'efficient' than using a class?

在什么时候,如果我继续添加字符串属性,是时候将结构转换为类了吗?

At what point, if I continued to add string properties, would it be time to convert the struct to a class?

我曾计划将此结构传递给以GDI为中心的应用程序.我一直认为结构在处理主要是值类型时表现更好.

I had planned to pass this struct around a GDI - centric application. I had always assumed structs were more performant when dealing with mainly value types.

推荐答案

如果您需要类提供的增强功能(例如继承),请进行切换.如果不是这样,则结构可能会轻一些",但是除非您预期到一些性能问题,例如在带有大量迭代的紧密循环内进行垃圾收集,否则必须使用 ref 只要您想对方法进行修改等,都会造成不必要的工作.(尽管在该示例中,销毁具有引用类型属性的结构也会导致GC).

If you need the enhanced capabilities that a class offers, such as inheritance, then switch. If not, a struct can be a bit "lighter," but unless you anticipate some performance issues, such as garbage collection inside of a tight loop with a LOT of iterations, the necessity to pass structs around with ref whenever you want a method to make modifications, etc can create unnecessary work. (Though, in that example, destroying a struct that has reference-type properties also causes GC).

实际的结果是:使用结构还是使用类取决于您的用例,而不是您拥有的属性的数量.

The practical upshot being: whether to use a struct or a class is a matter of your use case, not the number of properties that you have.

要很好地解释类和结构之间的区别以及相对优势和劣势,请

For a good explanation of the differences between and relative strengths and weakness of classes and structs, see this MSDN article.

要了解埃里克·利珀特(Eric Lippert)关于垃圾收集,结构和类的出色笔记,请查看他的回应这个问题.

For Eric Lippert's excellent note on garbage collection, structs and classes, see his response to this question.

这篇关于在Struct中存储引用类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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