代码改变世界

C#中,this在Struct和Class中的一个重要区别

2013-02-23 11:16  咒语  阅读(754)  评论(5编辑  收藏  举报

this 在Struct 中是可读可写

this 在Class中是只读

例子如下:

//Class
public class A
{
   public A(string json)
   {
        this = JsonSerializor.DeSerialize<T>(json) ; // 编译错误
   }
   public string Name{get;set;}
}
//Struct
public struct B
{
   public B(string json)
   {
        this = JsonSerializor.DeSerialize<T>(json) ; // OK,没有问题
   }
   public string Name{get;set;}
}