Inner class and Outer class in c#

前端 未结 4 1996
天命终不由人
天命终不由人 2021-01-05 19:25

how to implement inner outer classes in c#

i have two nested classes

like

class Outer
{
    int TestVariable = 0;
    class Inner
    {
              


        
相关标签:
4条回答
  • 2021-01-05 20:08

    No, C# does not have the same semantics as Java in this case. You can either make TestVariable const, static, or pass an instance of Outer to the constructor of Inner as you already noted.

    0 讨论(0)
  • 2021-01-05 20:11

    Short answer: No,

    You will somehow need to inject the TestVariable into your Inner class. Making your testVariable could potentially lead to undesired behaviour. My sugestion would be to inject it via the constructor.

    0 讨论(0)
  • 2021-01-05 20:18

    Make variable internal or pass to inner's constructor

    0 讨论(0)
  • 2021-01-05 20:25

    You can create an instance of inner class without even have outer class instance, what should happen in that case you think? That's why you can't use it

    Outer.Inner iner = new Outer.Inner(); // what will be InnerTestVariable value in this case? There is no instance of Outer class, and TestVariable can exist only in instance of Outer
    

    Here is one of the ways to do it

      class Outer
        {
            internal int TestVariable=0;
            internal class Inner
            {
                public Inner(int testVariable)
                {
                    InnerTestVariable = testVariable;
                }
               int InnerTestVariable; //Need to access the variabe "TestVariable" here
            }
            internal Inner CreateInner()
            {
                return new Inner(TestVariable);
            }
        }
    
    0 讨论(0)
提交回复
热议问题