我可以在 C# 中从同一类方法调用构造函数吗?

本文关键字:调用 类方法 构造函数 我可以 | 更新日期: 2023-09-27 18:35:19

我可以在C#中从同一类方法调用constructor吗?

例:

class A
{
    public A()
    {
        /* Do Something here */
    }
    public void methodA()
    {
        /* Need to call Constructor here */
    }
}

我可以在 C# 中从同一类方法调用构造函数吗?

简短的回答是否定的:)

不能将构造函数作为简单方法调用,但以下特殊情况除外

  1. 创建新对象:var x = new ObjType()

  2. 从相同类型的另一个构造函数调用构造函数:

     class ObjType
     {
         private string _message;
         // look at _this_ being called before the constructor body definition
         public ObjType() :this("hello")
         {}
         private ObjType(string message)
         {
             _message = message;
         }
     }
    
  3. 从构造函数
  4. 调用基类型构造函数:

     class BaseType 
     {
         private string _message;
         // NB: should not be private
         protected BaseType(string message)
         {
             _message = message;
         }
     }
     class ObjType : BaseType
     {
         // look at _base_ being called before the constructor body execution
         public ObjType() :base("hello")
         {}
     }
    

UPD。关于另一个答案中提出的初始化方法的解决方法 - 是的,这可能是一个好方法。但是由于对象的一致性,这有点棘手,这就是构造函数甚至存在的原因。任何对象方法都应该在一致(工作)状态下接收对象(this)。而且你不能保证它从构造函数调用方法。因此,任何编辑该初始化方法或将来调用构造函数的人(可能是您)都可以期望获得此保证,这大大增加了出错的风险。当您处理继承时,问题会被放大。

除了提供回答问题的答案外,解决问题的简单方法是定义一个从构造函数和方法调用的初始化方法:

class A
{
    private init()
    {
       // do initializations here
    }
    public A()
    {
        init();
    }
    public void methodA()
    {
        // reinitialize the object
        init();
        // other stuff may come here
    }
}

简而言之,您不能调用构造函数,但不必:)