英文:
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#中,我无法重新创建相同的静态内部类。
经过研究,我发现我只能执行以下操作之一:
- 使内部类classB为非静态,或将classB的所有成员设为静态。
- 在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<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;
}
}
}
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,
- Make the inner class classB non-static or make all the members of classB as static.
- 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<ClassB> classBs = new List<ClassB>();
public ClassA()
{
for (int i = 0; i < 10; i++)
{
this.classBs.Add(new ClassB());
}
}
public class ClassB
{
internal int value;
public ClassB()
{
this.value = 0;
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论