Skip to main content
 首页 » 编程设计

c#之类构造函数错误

2024年02月20日9myhome

正如我在上一个问题 Click here to view question 中所问的那样,因为我们知道子类中没有继承构造函数

我已经写好了代码

namespace TestConscoleApplication 
{ 
    abstract public class A 
    { 
       public int c; 
       public int d; 
 
    private  A(int a, int b) 
       { 
           c = a; 
           d = b; 
 
       } 
        public virtual void Display1() 
        { 
            Console.WriteLine("{0}{1}", c, d); 
        } 
    } 
    internal class B : A  
    { 
      protected  string Msg; 
 
      public B(string Err) 
 
        { 
            Msg = Err; 
 
        } 
 
        public  void Display() 
        { 
            Console.WriteLine(Msg); 
        } 
    } 
 
 
 
    class Program 
    { 
        static void Main(string[] args) 
        { 
            B ObjB = new B("Hello"); 
 
 
            Console.ReadLine(); 
        } 
    } 
} 

当我编译代码时显示错误

Error TestConscoleApplication.A.A(int, int) is inaccessible due to its protection level.

那为什么会报错。

请您参考如下方法:

通过将A 的唯一 构造函数设为私有(private),您可以防止在A 之外构造派生类。