<font color="black"><font color="#0000ff">class</font> Program<br/> {<br/> <font color="#0000ff">static</font> <font color="#0000ff">void</font> Main()<br/> {<br/> MyClass.NestedClass t1 = MyClass.New(); <font color="#008000">// ОК</font><br/> MyClass.NestedClass t2 = <font color="#0000ff">new</font> MyClass.NestedClass(); <font color="#008000">// Не должно компилироваться! Как сделать?</font><br/> }<br/> }<br/> <br/> <font color="#0000ff">public</font> <font color="#0000ff">static</font> <font color="#0000ff">class</font> MyClass<br/> {<br/> <font color="#0000ff">public</font> <font color="#0000ff">static</font> NestedClass New()<br/> {<br/> <font color="#0000ff">return</font> <font color="#0000ff">new</font> NestedClass();<br/> }<br/> <br/> <font color="#0000ff">public</font> <font color="#0000ff">sealed</font> <font color="#0000ff">class</font> NestedClass {}<br/> }</font><br/> <br/> <font color="gray">* This source code was highlighted with <a href="http://virtser.net/blog/post/source-code-highlighter.aspx"><font color="gray">Source Code Highlighter</font></a>.</font>
public static class MyClass
{
private static Func<NestedClass> _nestedClassFactory;
public static NestedClass New()
{
return _nestedClassFactory();
}
public sealed class NestedClass
{
private NestedClass()
{
}
static NestedClass()
{
_nestedClassFactory = () => new NestedClass();
}
}
}