我怎样才能同时拥有 public 和 private 空构造函数?

How can I have both public and private empty constructor?

我怎样才能同时拥有私有构造函数和 public 空构造函数?我需要一个空的私有构造函数,因为我首先使用 EF 编写代码。

documentation 说:

Does the Entity Framework require objects with public empty constructors?

While the default generated classes have an automatically supplied public parameterless constructor, there's nothing in the framework that requires that it be public. There must be a parameterless constructor, but it can be internal or private.

我的尝试:

    public class ImmediatePayment:Payment
    {
            private ImmediatePayment(){}
        
           //Problem
            public ImmediatePayment():basePayment(0){}
            
        //defining number other then 0 would make ImmediatePayment pointless, I could check the value of DeadlineDaysAfterOrder, but it seems really really nice to have a constructior without a number
            public ImmediatePayment(intDeadlineDaysAfterOrder):basePayment(DeadlineDaysAfterOrder){}
            
    }
            
public class Payment
{
      public int DeadlineDaysAfterOrder {get;private set;}
      
      private Payment(){}
      public Payment(int DeadlineDaysAfterOrder)
      {
      this.DeadlineDaysAfterOrder  = DeadlineDaysAfterOrder;
      }
}

答案是,您不能在同一个 class 中同时拥有空的私有构造函数和空的 public 构造函数。但在这种情况下,您不需要删除 private 构造函数。

必须有一个无参数的构造函数,可以是internalprivate。 但它不一定是private,它可以是public,如果生成的话也是默认的。

参考:Entity Framework 常见问题解答:实体 类 - Entity Framework 是否需要具有 public 空构造函数的对象?