新手(有C#经验),
这就是我想要做的:
public final class MyClass { public class MyRelatedClass { ... } } public class OtherRandomClass { public void DoStuff() { MyRelatedClass data = new MyClass.MyRelatedClass(); } }
这在Eclipse中给出了这个错误:
No enclosing instance of type BitmapEffects is accessible. Must qualify the allocation with an enclosing instance of type BitmapEffects (e.g. x.new A() where x is an instance of BitmapEffects).
这在C#中可以使用静态类,这里应该怎么做?
说:
When packages are stored in a file system (§7.2.1), the host system may
choose to enforce the restriction that
it is a compile-time error if a type
is not found in a file under a name
composed of the type name plus an
extension (such as .java or .jav) if
either of the following is true:
看到这个问题: multiple class declarations in one file
如果您希望创建一个名称空间来包含相关的类,那么您需要使用静态内部类.静态声明并不意味着一个实例 – 它们仍然可以被实例化 – 静态意味着它们可以被实例化而无需引用封闭类.由于封闭类仅用于分组,而不是数据,因此您可以安全地将其设置为静态.为了更清楚地表明封闭类仅用于分组,您应该将其声明为接口,以便它不能被实例化并且没有实现细节.
虽然就个人而言,我不会这样做 – 在Java中,包用于强制执行命名空间.使用内部类很快就变得很麻烦. (我试过了!)
翻译自:https://stackoverflow.com/questions/3039306/how-can-i-create-a-new-class-instance-from-a-class-within-a-static-class