用C#在Java中重新创建嵌套静态类

huangapple go评论75阅读模式
英文:

Recreating Nested Static Class in Java using C Sharp

问题

我正在将一段代码从Java移植到C#。在Java中,我有以下的类。

public class ClassA{
    ...
    private List<ClassA.ClassB> classBs = new ArrayList();

    public classA(){
        for(int i = 0; i < 10; i++){
            this.classBs.add(new ClassA.ClassB());
        }
    }

    public static class ClassB{
        private int value;

        public ClassB(){
            this.value = 0;
        }
    }
}

需要注意的重要事项是,在以下行中:

this.classBs.add(new ClassA.ClassB());

我们正在创建静态内部类的实例。

现在,在C#中,我无法重新创建相同的静态内部类。
经过研究,我发现我只能执行以下操作之一:

  1. 使内部类classB为非静态,或将classB的所有成员设为静态。
  2. 在classA之外定义classB。

两者都似乎无法复现Java的精确代码。我该如何继续?

英文:

I am working on porting a code from Java to C Sharp. In Java I have the following class.

public class ClassA{
    ...
    private List&lt;ClassA.ClassB&gt; classBs = new ArrayList();

    public classA(){
        for(int i = 0; i &lt; 10; i++){
            this.classBs.add(new ClassA.ClassB());
        }
    }

    public static class ClassB{
        private int value;

        public ClassB(){
            this.value = 0;
        }
    }
}

The important thing to notice is that, in line

> this.classBs.add(new ClassA.ClassB());

we are creating an instance of a Static Inner Class.

Now, in C sharp, I am not able to re-create the same static inner class.
After researching, I found I can only do the one of the following,

  1. Make the inner class classB non-static or make all the members of classB as static.
  2. Define classB outside classA.

Neither seem to recreate the exact code of Java. How do I proceed with this?

答案1

得分: 0

一个Java嵌套静态类与常规的C#嵌套类非常相似:

public class ClassA
{
    private List<ClassB> classBs = new ArrayList<ClassB>();

    public ClassA()
    {
        for (int i = 0; i < 10; i++)
        {
            this.classBs.add(new ClassB());
        }
    }

    public static class ClassB
    {
        internal int value;

        public ClassB()
        {
            this.value = 0;
        }
    }
}
英文:

A Java nested static class is very similar to a regular C# nested class:

public class ClassA
{
	private IList&lt;ClassB&gt; classBs = new List&lt;ClassB&gt;();

	public ClassA()
	{
		for (int i = 0; i &lt; 10; i++)
		{
			this.classBs.Add(new ClassB());
		}
	}

	public class ClassB
	{
		internal int value;

		public ClassB()
		{
			this.value = 0;
		}
	}
}

huangapple
  • 本文由 发表于 2020年10月5日 16:36:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/64205146.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定