名前の隠蔽

newキーワードを使用して継承元のメンバやメソッドを隠蔽する

サンプル

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace ConsoleApplication37
{
    class Program
    {
        static void Main(string[] args)
        {
            TestSub a = new TestSub();
 
            Console.WriteLine(a.data);
            a.testMethod1();
 
            Console.ReadKey();
        }
    }
 
    class TestMain
    {
        public int data = 10;
        public void testMethod1()
        {
            Console.WriteLine("TestMain->testMethod1");
        }
    }
 
    class TestSub : TestMain
    {
        // メンバの隠蔽
        new public int data = 90;
 
        // メソッドの隠蔽
        new public void testMethod1()
        {
            Console.WriteLine("TestSub->testMethod1");
        }
 
    }
}
 
 
 

メソッドのオーバーライドと異なるので注意すること
オーバーライドを使用するためにはオーバーライド用のキーワードを使用する必要がある

隠蔽されたメンバやメソッドを使用した場合はbaseキーワードを使用する

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace ConsoleApplication38
{
    class Program
    {
        static void Main(string[] args)
        {
            TestSub a = new TestSub();
 
            Console.WriteLine(a.data);
            a.testMethod1();
            a.testMethod2();
            a.testMethod3();
 
            Console.ReadKey();
        }
    }
 
    class TestMain
    {
        public int data = 10;
        public void testMethod1()
        {
            Console.WriteLine("TestMain->testMethod1");
        }
    }
 
    class TestSub : TestMain
    {
        // メンバの隠蔽
        new public int data = 90;
 
        // メソッドの隠蔽
        new public void testMethod1()
        {
            Console.WriteLine("TestSub->testMethod1");
        }
 
        // 継承元のメソッドを参照
        public void testMethod2(){
            base.testMethod1();
        }
 
        // 継承元のメンバを参照
        public void testMethod3()
        {
            Console.WriteLine(base.data);
        }
 
    }
}
 
 
 



最終更新:2011年05月25日 22:44