Q
含义
6
A
回答
11
埃里克利珀特有一个神话般的post在突变readonly struct
一段时间后,这将有助于澄清问题给你。甚至还有代码示例和测验!
要点是struct
服从价值语义和class
es不,所以this
必须意味着两个不同的东西。 this
对于class
是readonly
,但对于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);
}
}
相关问题
- 1. 含义类定义
- 2. 包含文件的含义
- 3. 不含定义为“包含”
- 4. 含义对象
- 5. 'pagerror.gif'的含义?
- 6. @android的含义
- 7. C++ typedef含义
- 8. 1000L的含义
- 9. 具体含义
- 10. setContextClassLoader含义
- 11. '+ ='的含义
- 12. ':'和'?'的含义
- 13. Javascript - '...'的含义
- 14. setContextClassLoader含义
- 15. PROPERTYKEY :: pid含义
- 16. 含义= games_ego
- 17. SEQUENCE_NEXT_HI_VALUE的含义
- 18. 含义 '*' 的
- 19. RegEx的含义
- 20. php {$ var}含义
- 21. RewriteRule含义
- 22. Golang struct {} {}含义
- 23. doublerule的含义
- 24. 'sp_renamedb'的含义
- 25. 含义10
- 26. 定义包含“
- 27. 含义参数
- 28. 含义在pd.DataFrame.all
- 29. Salesforce doc,' - '的含义
- 30. ++ operator overload C++含义
,我觉得在部队轩然大波,因为如果数百万的声音突然在恐怖中大声喊叫,并呼吁保持正确。请不要向我的C++同事展示这一点。 :-) – 2009-09-09 14:48:31
Eh,C++中的const是个谎言。在C++中,const通常意味着“我保证不改变这个东西”,而不是“我保证这个东西是不可变的”。 – 2009-09-09 15:05:20
不错的例子乔恩。这里你要证明的是,虽然结构可能是不可变的,但是包含struct的*变量*却不是。该变量仍然可以变化;这就是为什么它被称为变量。这只是使其变化的一种特别糟糕的方式。 – 2009-09-09 15:06:21