开发者

why can not create instance from any class out side of constructor?

开发者 https://www.devze.com 2023-01-01 04:26 出处:网络
why i generate instance outside of class. i give开发者_高级运维 inheritance snifC to sinifD i need to create instance sinifC sinifc= new sinifC() in SinifD out side of constructor?

why i generate instance outside of class. i give开发者_高级运维 inheritance snifC to sinifD i need to create instance sinifC sinifc= new sinifC() in SinifD out side of constructor?

  public  class sinifC
    {
       public  void method3()
        {
            Console.WriteLine("Deneme3");
        }
    }

   public class sinifD : sinifC
    {
        void method4()
        {
            Console.WriteLine("Deneme4");
        }

        public sinifD()
        {
            sinifC sinifc = new sinifC();
            sinifc.method3();
        }
    }

i want to make it below:


    public  class sinifC
    {
       public  void method3()
        {
            Console.WriteLine("Deneme3");
        }
    }

   public class sinifD : sinifC
    {
        void method4()
        {
            Console.WriteLine("Deneme4");
        }


            sinifC sinifc = new sinifC();
            sinifc.method3();

    }

Error: Invalid token '(' in class, struct, or interface member declaration


doesn't

        sinifC sinifc = new sinifC();
        sinifc.method3();

need to be inside a method?

You seem to want to create an instance of an object and call its method inside the body of the class, but you need to have it happen inside a method.


You don't have to write the code in the constructor, but you do have to write the code in some method. You're currently just writing the code anywhere in your class. If you don't want to have to create an instance of your D class to do this you could create a static method in your D class that creates the instance of the C class (you could even have a static constructor).


The only valid instructions in the body of a class are declarations (optionally including initialization for fields). A method call is not a valid instruction here, it has to be inside a method


You do not need to create an instance of sinifC - you are using inheritace by extending it.

class Program
{
    static void Main(string[] args)
    {
        sinifD s = new sinifD();

        // call method3 on sinfiD
        s.method3();
    }
}

public  class sinifC
{
   public  void method3()
    {
        Console.WriteLine("Deneme3");
    }
}

public class sinifD : sinifC
{
    // sinifD inheritrs mehtod3 from sinifD

    // method 4 is protected, so only classes in the class hierachy see that method
    void method4()
    {
        Console.WriteLine("Deneme4");
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消