简体   繁体   English

C#.Net强制转换和实例化内存分配

[英]C#.Net Casting and Instantiating Memory Allocation

Can some one explain me what is the different between this type of usage as performance vice. 有人可以解释一下这种类型的性能副工具有什么区别吗? These are simply function callings on two inherited classes. 这些只是对两个继承的类的函数调用。 First one uses the advantage of inheritance and second one discard it. 第一个利用继承的优势,第二个放弃继承。

class ClassA 
{
    public void X()
    {
        Console.WriteLine("ClassA: X()");
    }
}

class ClassB : ClassA
{
    new public void X()
    {
        Console.WriteLine("ClassB: X()");
    }
}

class CheckMemory
{
    public void testMemory ()
    {  
        //Code block 1
        ClassB bob1 = new ClassB();
        ClassA aob1 = bob1;

        aob1.X();
        bob1.X();

        //Code block 2 
        ClassB bob2 = new ClassB();
        ClassA aob2 = new ClassA();

        aob2.X();
        bob2.X();
    }

}

In the first case instead of allocating a new Object we are reusing it ie both bob1 and aob1 are pointing to the same instance of an object on the Heap. 在第一种情况下,我们没有重用它,而是重用了它,即bob1和aob1都指向堆上一个对象的同一实例。

Where as in the second block you are creating two different instance of two different classes they occupy two memory locations in the heap , instead of the first one. 与在第二个块中一样,您正在创建两个不同类的两个不同实例,它们在堆中占据了两个内存位置,而不是第一个。

So the first one is memory efficient then the first , I hope this explanation helps. 因此,第一个是内存高效的,然后第一个是内存高效的,我希望这个解释有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM