c#中的引用类型和值类型有什么区别? [英] What is the difference between a reference type and value type in c#?

查看:24
本文介绍了c#中的引用类型和值类型有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几个月前有人问过我这个问题,我无法详细解释.C#中的引用类型和值类型有什么区别?

Some guy asked me this question couple of months ago and I couldn't explain it in detail. What is the difference between a reference type and a value type in C#?

我知道值类型是 intboolfloat 等,引用类型是 delegateinterface 等等,或者这也是错的?

I know that value types are int, bool, float, etc and reference types are delegate, interface, etc. Or is this wrong, too?

你能用专业的方式给我解释一下吗?

Can you explain it to me in a professional way?

推荐答案

你的例子有点奇怪,因为 intboolfloat> 是特定类型,接口和委托是类型的 kinds - 就像 structenum 是值类型的种类.

Your examples are a little odd because while int, bool and float are specific types, interfaces and delegates are kinds of type - just like struct and enum are kinds of value types.

我写了an对引用类型和值类型的解释在本文中.我很乐意就您感到困惑的任何部分进行扩展.

I've written an explanation of reference types and value types in this article. I'd be happy to expand on any bits which you find confusing.

TL;DR"版本是考虑特定类型的变量/表达式的值是什么.对于值类型,值就是信息本身.对于引用类型,值是一个引用,它可能为 null,也可能是导航到包含信息的对象的一种方式.

The "TL;DR" version is to think of what the value of a variable/expression of a particular type is. For a value type, the value is the information itself. For a reference type, the value is a reference which may be null or may be a way of navigating to an object containing the information.

例如,将变量想象成一张纸.它上面可以写有值5"或false",但它不能有我的房子……它必须有方向到我的房子.这些方向相当于一个参考.特别是,两个人可能有不同的纸,上面写着到我家的相同方向——如果一个人按照这些方向把我的房子涂成红色,那么第二个人也会看到这种变化.如果他们都在纸上单独照片我的房子,那么一个人给他们的纸上色根本不会改变另一个人的纸.

For example, think of a variable as like a piece of paper. It could have the value "5" or "false" written on it, but it couldn't have my house... it would have to have directions to my house. Those directions are the equivalent of a reference. In particular, two people could have different pieces of paper containing the same directions to my house - and if one person followed those directions and painted my house red, then the second person would see that change too. If they both just had separate pictures of my house on the paper, then one person colouring their paper wouldn't change the other person's paper at all.

这篇关于c#中的引用类型和值类型有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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