1. 程式人生 > 實用技巧 >Java-C#-內部類

Java-C#-內部類

Java

code:

public class Outer{
    private int outerNum = 1;
    
    public int getOuterNum() {
		return outerNum;
	}
    
    public class Inner{
        public void func(){
            //可以直接訪問外部類的成員
            outerNum++;
        }
    }
    
    public void func(){
    	var inner=new Inner();
    	inner.func();
    }
}

public class Program {
	
	public static void main(String[] args) {
		
		var outer=new Outer();
		System.out.println(outer.getOuterNum());
		
		outer.func();
		System.out.println(outer.getOuterNum());
		
		var inner=outer.new Inner();
		inner.func();
		System.out.println(outer.getOuterNum());
	}
	
}

result:

C#

code:

public class Outer
{
    private int outerNum=1;

    public int OuterNum { get => outerNum;}

    public class Inner
    {
        public void Func()
        {
            //錯誤,無法訪問外部類的非靜態成員
            //outerNum++;

            //通過外部類的例項來訪問非靜態成員
            var outer = new Outer();
            outer.outerNum++;
        }
    }

    public void Func()
    {
        var inner = new Inner();
        inner.Func();
    }
}

public static async Task Main(string[] args)
{
    var outer = new Outer();
    Console.WriteLine(outer.OuterNum);

    outer.Func();
    Console.WriteLine(outer.OuterNum);

    var inner = new Outer.Inner();
    inner.Func();
    Console.WriteLine(outer.OuterNum);

    await Task.CompletedTask;
}

result: