C# string与String区别

  C#是区分大小写的,但是我却发现C#中同时存在String与string,于是我很困惑,于是我上网搜索了一下,于是我了解了一些小知识。
  MSDN中对string的说明:string is an alias for String in the .NET Framework。string是String的别名而已,string是c#中的类,String是Framework的类,C# string 映射为 Framework的 String。如果用string,编译器会把它编译成String,所以如果直接用String就可以让编译器少做一点点工作。
  如果使用C#,建议使用string,比较符合规范 。 string始终代表 System.String(1.x) 或 ::System.String(2.0) ,String只有在前面有using System;的时候并且当前命名空间中没有名为String的类型(class、struct、delegate、enum)的时候才代表System.String。
  string是关键字,String不是,也就是说string不能作为类、结构、枚举、字段、变量、方法、属性的名称,而String可以。

1. C#到底是什么时候传引用?什么时候传值?

  传值的情况:
  Struct、Enumeration、Numeric(Integral/Floating/decimal)、bool
  传引用的情况:
  class、Delegate、Interface

  当使用操作符"="以及函数传参数的时候:

  传值的结果是把原对象复制了一份,接收者指向原对象。
  传引用的结果是直接让接收者指向原对象。

   有人说,我硬要把值当引用传怎么办?
    a.用ref关键字
    b.用数组,数组是class
    c.凉拌 😐

2. String传值还是传引用

  C#的String声明是class String,当然是传引用。不过,之所以有这个疑惑,多数是因为这个情况:

string a = "aaa";
string b = a;
b = "bbb";

   或者是这么几行代码:

public void Swap(string s1, string s2)
{
    string temp=s1;
    s1=s2;
    s2=temp;
}

  这时候结果一打印,结果发现a的值还没有变,Swap也没有成功,这时候就会有幻觉:是不是没有传引用啊?
  呵呵,string不会这么粗暴的打乱“声明为class就是传引用”这种规则的。
  分析一下:

string a = "aaa";  //=> a----->new String("aaa")
string b = a;      //=> b----->a, 传引用
b = "bbb";         //=> b----->new String("bbb"), 传引用,b指向了一个新的字符串,a并没有变。

  Swap函数也是这样,比如说传了a, b进去(a=“aaa”, b=“bbb”),

//s1----->a, s2----->b
string temp=s1;  //temp----->s1----->a
s1=s2;           //s1----->s2----->b;
s2=temp;         //s2----->temp----->a

  结果是,s1和s2确实是Swap了,但是这种结果并不会影响到a和b

3. string和String有什么区别?

  MSDN中对string的说明:string is an alias for String in the .NET Framework
呵呵string是String的别名而已,都是一家。

4. String为什么是Immutable,怎么实现的?

  String为什么是Immutable,怎么实现的?
  immutable:对象一旦生成不可改变。关于怎么实现的,在明白了问题2之后很好办,只要不提供任何修改自己成员变量的方法就可以了。顺便声明为sealed,防止不清楚的后来者违反规定 😃
  String每个看似修改了成员变量的方法,事实上都返回了一个新的String。比如String.Replace函数,事实上并没有改变原来的串,这也是为什么只有让str = str.Replace( foo, bar )才真正完成替换的原因。

下面是.NET C# VB.NET IL的类型对应表:

NETC#VB.NETIL值或引用
System.BooleanboolBooleanboolValue
System.BytebyteByteunsigned int8Value
System.CharcharCharcharValue
System.DateTime-Date-Value
System.DecimaldecimalDecimal-Value
System.DoubledoubleDoublefloat64Value
System.Int16shortShortint16Value
System.Int32intIntegerint32Value
System.Int64longLongint64Value
System.ObjectobjectObjectobjectReference
System.SBytesbyte-int8Value
System.SinglefloatSinglefloat32Value
System.StringstringStringstringReference
System.UInt16ushort-unsigned int16Value
System.UInt32uint-unsigned int32Value
System.UInt64ulong-unsigned int64Value
  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值