Java-C#-内部类

Java

code:

public class Outer{
    private int outerNum = 1;
    
    public int getOuterNum() {
		return outerNum;
	}
    
    public class Inner{
    	//错误,非静态内部类不能有静态成员
    	//static int num;

        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
    {
        static int num;

        public void Func()
        {
            //错误,无法访问外部类的非静态成员
            //outerNum++;

            //通过外部类的实例来访问非静态成员
            var outer = new Outer();
            outer.outerNum++;
        }
    }

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

public class Program
{
    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:

posted @ 2020-10-28 13:44  自笑非  阅读(88)  评论(0编辑  收藏  举报