为什么字符串是引用类型,但是从其他引用类型的行为有所不同? [英] Why string is a reference type, but behaves differently from other reference types?
问题描述
我们知道,字符串是引用类型,所以我们有
We know that string is a reference type , so we have
string s="God is great!";
但是,如果我声明类说员工是引用类型,那么为什么下面一块相同的音符?代码不能正常工作
but on the same note if i declare class say Employee which is a reference type so why below piece of code does not work ?
Employee e = "Saurabh";
2 - 我们如何真正确定一个类型是引用类型或值类型?
2- How do we actually determine if a type is a reference type or value type?
推荐答案
该代码会,如果你有一个字符串到的隐式转换工作员工
。基本上一个字符串文字是类型字符串
- 即它的值是一个字符串引用(而且是一个实习的)。你可以,如果有这两种类型之间的转换将一种类型的值只能分配给另一个类型的变量 - 无论是用户定义或内置在这种情况下,没有从字符串$转换C $ C>为
员工
,因此错误。
That code would work if you had an implicit conversion from a string to an Employee
. Basically a string literal is of type string
- i.e. its value is a string reference (and an interned one at that). You can only assign a value of one type to a variable of another type if there's a conversion between the two types - either user-defined or built in. In this case, there's no conversion from string
to Employee
, hence the error.
相反,一些其他的答案,类型不必须是的相同的 - 比如,这是罚款:
Contrary to some other answers, the types don't have to be the same - for example, this is fine:
object x = "string literal";
这很好,因为有一个从字符串$ C $隐式引用转换C>到
对象
。同样,你可以这样写:
That's fine because there's an implicit reference conversion from string
to object
. Likewise you can write:
XNamespace ns = "some namespace";
由于有一个的从字符串的XNamespace
。
because there's an implicit conversion from string to XNamespace
.
要回答你的第二个问题:看是否在.NET中使用类型是值类型或引用类型... 结构
和枚举
类型是值类型;一切(类,委托,接口,数组)是引用类型。这不包括指针类型,这是一个有点不同:)
To answer your second question: to see if a type in .NET is a value type or a reference type... struct
and enum
types are value types; everything else (class, delegate, interface, array) is a reference type. That's excluding pointer types, which are a bit different :)
这篇关于为什么字符串是引用类型,但是从其他引用类型的行为有所不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!