为什么不能在C#中设置“ this”

问题描述

我已经检查了链接"Why can't I set “this” to a value in C#?",并且我知道this是只读的。换句话说,它(内容)不能分配给另一个新对象。我只是想知道C#中这种约束的哲学或考虑因素。如果原因是为了保证内存管理的安全性,则C#将使用垃圾回收器,并确定将来对对象的使用情况。

    public class TestClass
    {
        private int Number;
        public TestClass()
        {
            this.Number = 0;
        }
        public TestClass(TestClass NewTestClass)
        {
            this = NewTestClass;        //  CS1604  Cannot assign to 'this' because it is read-only
        }

    }

结果,似乎需要对成员进行一次更新。

public TestClass(TestClass NewTestClass)
{
    this.Number = NewTestClass.Number;  //  Update members one by one.
}

欢迎任何评论。

注意:为澄清起见,C ++部分已删除。

解决方法

我认为您不熟悉取消引用指针的含义。

让我们看看这种方法:

void TestClass::SetThisTest() {
    *this = TestClass(this->IncreaseNumber().GetNumber());      //  Assign new object to *this
}

您认为自己正在替换this,但不是。您将替换this指向的内容。差异很大。 *this!= this

尝试一下:

void TestClass::SetThisTest() {
    std::cout << "this' address is " << std::to_address(this) << std::endl;
    *this = TestClass(this->IncreaseNumber().GetNumber()); // shallow copy!
    std::cout << "Now this' address is " << std::to_address(this) << std::endl;
}

地址没有变化,但是this点的值却发生了变化。 您正在调用(在这种情况下)默认的浅表副本

you just aren't allowed to be that direct about it可以很容易地在C#中完成。

这是您的C ++类的C#等效项:

public sealed class ThisTest
{
    private int _myNumber;

    public ThisTest() { }

    public ThisTest(int number) { _myNumber = number; }

    public static void ShallowCopy(ThisTest to,ThisTest from)
    {
        to._myNumber = from._myNumber;
    }

    public int GetNumber() => _myNumber;

    public ThisTest IncreaseNumber()
    {
        _myNumber += 1;
        return this;
    }

    public void SetThisTest()
    {
        ShallowCopy(this,new ThisTest(this.IncreaseNumber().GetNumber()));
    }
}
,

因为“ this”是对您实例化的对象的引用,因此只能从对象本身进行访问。

为什么“这个”除了自我指称外,什么都不需要?

var s = new Sample { Title = "My Sample" };
//in this case,I want to see a string representation of "s"
Debug.WriteLine(s.ToString());

//in this case,we might want a copy
var s2 = (Sample)s.MemberwiseClone();

public class Sample
{
    public string Title { get; set; }

    public override string ToString()
    {
         //it wouldn't make sense to reference another object's "Title",would it?
         return this.Title;
    }
}
,

在C#中是一个“关键字”,用于引用该类的当前实例。

您无法为关键字分配值,另一个示例是关键字“ base”,我们无法分配值。例如。 base =“ text”。

我们可以通过包含第一个类的另一个类为对象分配值。

public class TestClassParent
{
    private TestClass _testObject;

    public TestClassParent(TestClass testOject)
    {
        this._testObject = testObject;
    }
}

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...