W
W
Weageoo2011-08-21 03:23:57
C++ / C#
Weageoo, 2011-08-21 03:23:57

C#. Prevent nested class instantiation?

The situation in a vacuum:

<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>

How to prevent the creation of an instance of a nested class by everyone except the class containing this nested class? It seems that even the pattern was like this, or there is an attribute, but I forgot everything ...

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
VenomBlood, 2011-08-21
@Weageoo

Specifically, in the case of a static outer class, you can do the following:
Add parameters to the constructor to taste.

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();
        }
    }
}

W
Weageoo, 2011-08-21
@Weageoo

[System.Security.Permissions.ReflectionPermission(System.Security.Permissions.SecurityAction.Assert)]. Isn't it working now?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question