含义

2009-09-09 100 views
6

根据MSDN(所述C# spec的11.3.6节):含义

在一个 结构的实例构造,this对应的out 参数的结构类型,以及 的 一个结构的实例函数成员内,this对应于结构类型的ref 参数。在这两种情况下 ,this被分类为 变量,它可以修改 的量, 功能件是通过 调用分配给this或通过传递this 作为refout参数的整个结构体。

我不明白这一点。 this对于一个结构体而言与一个类不同的是什么?代码示例赞赏

回答

11

埃里克利珀特有一个神话般的post在突变readonly struct一段时间后,这将有助于澄清问题给你。甚至还有代码示例和测验!

要点是struct服从价值语义和class es不,所以this必须意味着两个不同的东西。 this对于classreadonly,但对于struct不是。下面的代码是合法的

struct Point { 
    public int x; 
    public int y; 

    public Point(int x, int y) { 
     this.x = x; 
     this.y = y; 
    } 

    public void DoGoTime() { 
     GoTime(ref this); 
    } 

    public static void GoTime(ref Point p) { 
     p.x = 100; 
     p.y = 100; 
    } 
} 

但没有如果“struct”改为“class”。

6

当您处理结构时,您正在处理值类型。

在一个类中,“this”是对当前实例的引用。这可让您通过设置类的属性/字段来变更类实例。

但是,如果你在一个结构中,事情的行为是不同的。当你在一个结构体的方法中时,“this”可以让你修改结构体。然而,如果你在一个方法中使用它,你几乎总是处理一个“原始”结构的副本。

例如:

struct Test 
{ 
    int i; 
    void Mutate() { 
     this.i += 1; 
    } 
} 

当您使用此:

void MutateTest(Test instance) 
{ 
    instance.Mutate(); 
} 

{ 
    Test test = new Test(); 
    test.i = 3; 
    Console.WriteLine(test.i); // Writes 3 
    test.Mutate(); // test.i is now 4 
    Console.WriteLine(test.i); // Writes 4 
    MutateTest(test); // MutateTest works on a copy.. "this" is only part of the copy itself 
    Console.WriteLine(test.i); // Writes 4 still 
} 

现在,陌生的一部分 - 这是有效的,什么是报价在说:

struct Test 
{ 
    public Test(int value) 
    { 
     this.i = value; 
    } 
    int i; 

    void Mutate(int newValue) { 
     this = new Test(newValue); // This wouldn't work with classes 
    } 
} 


/// 
{ 
    Test test = new Test(); 
    test.i = 3; 
    Console.WriteLine(test.i); // Writes 3 
    test.Mutate(4); 
    Console.WriteLine(test.i); // Writes 4 
6

Jason的回答和Eric的帖子显示了this的一个方面,这很有趣......但还有另一个更令人担忧:

即使类型是不可变的,您也可以在方法内重新分配this

为了演示,我们将使用存储在一个非只读变量结构,但其中包含的只读域:

using System; 

public struct LooksImmutable 
{ 
    private readonly int value; 
    public int Value { get { return value; } } 

    public LooksImmutable(int value) 
    { 
     this.value = value; 
    } 

    public void GoCrazy() 
    { 
     this = new LooksImmutable(value + 1); 
    } 
} 

public class Test 
{ 
    static void Main() 
    { 
     LooksImmutable x = new LooksImmutable(5); 
     Console.WriteLine(x.Value); 
     x.GoCrazy(); 
     Console.WriteLine(x.Value); 
    } 
} 
+0

,我觉得在部队轩然大波,因为如果数百万的声音突然在恐怖中大声喊叫,并呼吁保持正确。请不要向我的C++同事展示这一点。 :-) – 2009-09-09 14:48:31

+1

Eh,C++中的const是个谎言。在C++中,const通常意味着“我保证不改变这个东西”,而不是“我保证这个东西是不可变的”。 – 2009-09-09 15:05:20

+0

不错的例子乔恩。这里你要证明的是,虽然结构可能是不可变的,但是包含struct的*变量*却不是。该变量仍然可以变化;这就是为什么它被称为变量。这只是使其变化的一种特别糟糕的方式。 – 2009-09-09 15:06:21