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

K. *_*uru 3 .net c# constructor

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

例子:

class A
{
    public A()
    {
        /* Do Something here */
    }

    public void methodA()
    {
        /* Need to call Constructor here */
    }
}
Run Code Online (Sandbox Code Playgroud)

pku*_*rov 5

简短的回答是否定的:)

除了这些特殊情况外,您不能将构造函数作为简单方法调用:

  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;
         }
     }
    
    Run Code Online (Sandbox Code Playgroud)
  3. 您从构造函数调用基类型构造函数:

     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")
         {}
     }
    
    Run Code Online (Sandbox Code Playgroud)

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