【问题标题】:How to overwrite a point in memory in c#?如何在c#中覆盖内存中的一个点?
【发布时间】:2018-04-27 18:18:08
【问题描述】:

我想拥有以下功能:

var item0 = new Item();
var item1 = item0;
item0 = null;

Console.WriteLine(item1 == null); // true

所以我会覆盖 item0 和 item1 指向的内存。 我想也许我可以用指针来做到这一点..?但是,当我尝试声明一个项目指针时:

Item* itemPointer;

我遇到了一个错误。有什么想法吗?

【问题讨论】:

  • 我不知道您建议的语法适用于哪种语言 - 如果这样做会引入很多难以发现的错误
  • 您可以使用 Marshaling 释放指针,但如果该指针在其他地方拥有,您很可能会遭受可怕的死亡。 I guess you could check this for a start
  • 我很好奇为什么你想这样做?以这种方式直接修改内存(并放弃运行时提供的所有安全性)的目的是什么?
  • @UnholySheep:我猜他不想在内存中留下任何垃圾。
  • 我完全同意@UnholySheep,但在我看来他只是想制作该项目的新副本而不是克隆。

标签: c#


【解决方案1】:

从 C# 7 开始你可以使用Ref Locals:

var item0 = new Item();
ref var item1 = ref item0;
item0 = null;

Console.WriteLine(item1 == null); // true  
// THIS WORKS!          

Ref returns and ref locals 的引入主要是为了避免在时间敏感的场景中复制大型结构,比如必须处理大量向量数组的游戏。我没有看到将它们与引用类型一起使用的优势。它们往往会使代码难以理解,因此我会将它们的使用限制在特殊和罕见的情况下。

【讨论】:

    【解决方案2】:
    var item0
    {
       get{return item0;}
       set
       {
         item0 = value;
         item1 = item0;
       }
    }
    

    每次 item0 的值发生变化时,这样的事情都会覆盖 item1 的值。

    【讨论】:

      【解决方案3】:

      C# 中没有本地别名/引用 但是有一个 ref 关键字用于参数:

      static void RefClean(ref String arg){
          arg = null;
      }
      static void Main(string[] args)
      {
          var test = "Hello";
          Console.WriteLine(test == null);
          RefClean(ref test);
          Console.WriteLine(test == null);
      }
      


      对于指针,您需要 unsafe 关键字,并且您只能使用非托管类型(原始类型和由它们构建的结构),这排除了您使用对象/引用的情况。有关概述,请参阅https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/unsafe-code-pointers/pointer-types

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-11
        • 1970-01-01
        相关资源
        最近更新 更多