C# 是否有等效的 Java 静态嵌套类? [英] Does C# have an equivalent of Java static nested class?

查看:32
本文介绍了C# 是否有等效的 Java 静态嵌套类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将 Java 转换为 C# 并具有以下代码(参见 Java 上下文中的讨论 关于它的使用).一种方法可能是创建一个单独的文件/类,但是否有一个 C# 习惯用法可以保留 Java 代码中的意图?

I am converting Java into C# and have the following code (see discussion in Java Context about its use). One approach might be to create a separate file/class but is there a C# idom which preserves the intention in the Java code?

   public class Foo {

    // Foo fields and functions
    // ...
        private static class SGroup {
            private static Map<Integer, SGroup> idMap = new HashMap<Integer, SGroup>();

            public SGroup(int id, String type) {
    // ...
            }
        }
    }

推荐答案

看看这个http://blogs.msdn.com/oldnewthing/archive/2006/08/01/685248.aspx

我特别关注

换句话说,Java 内部类是不可用的语法糖到 C#.在 C# 中,你必须这样做手动.

In other words, Java inner classes are syntactic sugar that is not available to C#. In C#, you have to do it manually.

如果你愿意,你可以创建自己的糖:

If you want, you can create your own sugar:

class OuterClass {
 ...
 InnerClass NewInnerClass() {
  return new InnerClass(this);
 }
 void SomeFunction() {
  InnerClass i = this.NewInnerClass();
  i.GetOuterString();
 }
}

您想用 Java 编写的地方new o.InnerClass(...) 你可以写C# o.NewInnerClass(...) 或 new内部类(o,...).是的,这只是一个一堆移动新词.就像我说的,这只是糖.

Where you would want to write in Java new o.InnerClass(...) you can write in C# either o.NewInnerClass(...) or new InnerClass(o, ...). Yes, it's just a bunch of moving the word new around. Like I said, it's just sugar.

这篇关于C# 是否有等效的 Java 静态嵌套类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆