How to call protected constructor in c#?

后端 未结 8 1859
不知归路
不知归路 2021-02-19 00:51

How to call protected constructor?

public class Foo{
  public Foo(a lot of arguments){}
  protected Foo(){}
}
var foo=???

This obviously fails

8条回答
  •  孤街浪徒
    2021-02-19 01:10

    may be this will help:

    abstract parent class:

     public abstract class Animal
        {
    
            private string name;
    
            public Animal(string name)
            {
    
                this.Name = name;
            }
    
            public Animal() { }
            public string Name
            {
    
                get { return this.name; }
    
                set { this.name = value; }
    
            }
    
            public virtual void talk()
            {
    
                Console.WriteLine("Hi,I am  an animal");
    
            }
    
    
        }
    

    class with protected constructor:

    public class Lion : Animal
        {
            private string yahoo;
    
            protected Lion(string name) : base(name)
            {
    
                this.Yahoo = "Yahoo!!!";
            }
    
            public string Yahoo
            {
                get
                {
                    return yahoo;
                }
    
                set
                {
                    yahoo = value;
                }
            }
    
            public Lion() { }
        }
    

    class Kiara derived from Lion class :

     public class Kiara : Lion
        {
    
            public Kiara(string name) : base(name)
            {
    
            }
    
            public override void talk()
            {
    
                Console.WriteLine("HRRRR I'm a Kiara");
    
            }
    
            public Kiara() { }
    
        }
    

    class Simba derived from Lion class :

        public class Simba : Lion
        {
    
            public Simba(string name) : base(name)
            {
    
            }
    
            public override void talk()
            {
    
                Console.WriteLine("HRRRR I'm a {0}  and this is my daughter:{1} {2}", 
                new Simba("Simba").Name, 
                new Kiara("Kiara").Name, 
                new Simba("Simba").Yahoo);
            }
    
    
            public Simba() { }
    
        }
    

    implementation in main function:

           public static void Main(string[] args)
            {
    
    
                Animal lion = new Simba();
                lion.Name = "Simba";
                lion.talk(); 
                Animal lion1 = new Kiara();
                lion1.Name = "Kiara";
                lion1.talk();
            }
    

提交回复
热议问题