2016-08-17 38 views
-3

我有下面的代码,它运行,但我不知道它是否可以简化。即使它是NULL,我也可以在一个Zeroton上调用一个析构函数吗?我可以从私有构造函数调用析构函数并使用垃圾回收吗?

我想我可以简化我的代码,但我不知道如何。

代码:

class Program 
{ 
    static void Main(string[] args) 
    { 
     var zeroten = new Zeroton(); 
     var w = zeroten.ToString(); 
     var x = zeroten.Equals(w); 
     var y = zeroten.GetHashCode(); 
     var z = zeroten.GetType(); 
     if(z == typeof(Zeroton)) 
     { 
      zeroten = null; 
     } 
    } 
} 

using System; 
using System.Threading; 

public class Zeroton : IDisposable 
{ 
    private Zeroton zeroten; 
    public override bool Equals(object obj) 
    { 
     return BitConverter.IsLittleEndian; 
    } 

    public override string ToString() 
    { 
     return GC.MaxGeneration.ToString(); 
    } 

    public override int GetHashCode() 
    { 
     return GC.MaxGeneration; 
    } 

    public Zeroton() 
    { 
     GC.Collect(); 
     Zeroton z = null; 
     try 
     { 
      NullifyMemoryPressure(); 
      GC.Collect(); 
      DoNothingForAwhileThenStop(); 
     } 
     catch (Exception ex) 
     { 
      DoNothingForAwhileThenStop(); 
      SuppressError(); 
      GC.GetTotalMemory(true); 
     } 
     if (true) 
     { 
      DoNothingForAwhileThenStop(); 
      GC.AddMemoryPressure(GC.MaxGeneration); 
      GC.RemoveMemoryPressure(GC.MaxGeneration); 
     } 
     GC.KeepAlive(z); 
     GC.Collect(); 
    } 

    private Zeroton DoNothingForAwhileThenStop() 
    { 
     Thread.Sleep(GC.MaxGeneration); 
     GC.Collect(); 
     NullifyMemoryPressure(); 
     GC.Collect(); 
     return zeroten; 
    } 

    private void NullifyMemoryPressure() 
    { 
     GC.Collect(); 
     GC.AddMemoryPressure(GC.MaxGeneration); 
     GC.RemoveMemoryPressure(GC.MaxGeneration); 
     GC.Collect(); 
     GC.KeepAlive(zeroten); 
    } 

    void IDisposable.Dispose() 
    { 
     if (null == null) 
     { 
      NullifyMemoryPressure(); 
      GC.Collect(); 
      this.zeroten = null; 
      GC.Collect(); 
      GC.CancelFullGCNotification(); 
     } 
     DoNothingForAwhileThenStop(); 
    } 

    int? SuppressError() 
    { 
     GC.CancelFullGCNotification(); 
     DoNothingForAwhileThenStop(); 
     GC.Collect(); 
     NullifyMemoryPressure(); 
     return null; 
    } 
} 
+0

C#没有析构函数。推测你的意思是一个终结者,但你的代码没有终结者。 – Servy

+0

要间接回答所问的问题......你不能对任何“null”对象做任何事情,因为这意味着没有任何对象可以采取行动。我也打赌你可以通过不做任何你认为你在做的事情来简化你的代码。 –

回答

1

我觉得你有关于如何这一切工作完全是一个误会。 C#没有析构函数。 C#中没有办法强制垃圾收集器收集任何对象。永远。

你有什么是终结者。然而,重要的是要记住,终结器处理非托管资源...即非内存的东西。此外,我们有IDisposable模式,我们可以用确定性的方式调用终结器...但是,IDisposable处理非托管资源,而不是内存。

换句话说,你绝对可以简化代码,因为所有这些GC.Collects()相对没有做任何你Zeroton类型。

0

unsafe关键字就是为此而创建的。

public class Program 
{ 
    unsafe 
    { 
     var zeroten = new Zeroton(); 
     Monitor.Enter(zeroten); 
     ~this(); // this calls teh destructor 
     Environment.Exit(); 
    } 
} 
+0

我想进入你的显示器。咦!呵呵! Droolz。 或监视你的入口。 –

+0

请参阅:'Monitor.Pulse' https://msdn.microsoft.com/en-us/library/system.threading.monitor.pulse(v=vs.110).aspx –

相关问题