How to call constructor inside the class?

匿名 (未验证) 提交于 2019-12-03 08:39:56

问题:

I want to call constructor inside the class like: public class Myclass(){

   public MyClass(){       //......    }     public MyClass(int id):this(){       //......    }     private void Reset(){       //.....       this = new MyClass(id);    //here I want to call constructor       //......    } } 

but it is not working. Is it possible and how can I do it if Yes?

回答1:

You can't. But what you could do is split the constructor logic into an Initialize method that then reset could call.

   public MyClass(){    //......    }     public MyClass(int id):this(){       Initialize(id);    }     private void Initialize(int id){    //....    }     private void Reset(){       //.....       Initialize(id);       //......    } } 


回答2:

Simple answer: You can't.

Slightly more complicated answer: Move your initialization logic into a separate method that can be called from the constructor and your Reset() method:

public class MyClass {     public int? Id { get; }      public MyClass()     {         Initialize();     }      public MyClass(int id)     {         Initialize(id);     }      public Reset()     {         Initialize();     }      private Initialize(int? id = null)     {         // initialize values here instead of the constructor         Id = id;     } } 


回答3:

No this is not possible. You cannot assign to this.

You could however let Reset() return a new instance of MyClass so the caller code could say:

public class MyClass {     public MyClass Reset()     {         return new MyClass();     } }  MyClass c = new MyClass(); c = c.Reset(); 

Or you could implement the Reset method in such a way that all fields are reinitialized to their default values.



回答4:

You can call a constructor for your class inside your class (in fact this is often done with factory methods):

public class MyClass {     public static MyClass Create()     {         return new MyClass();        } } 

But you can't change the value of the this reference inside the class. You should instead have your "Reset()" method set the fields back to their default values.



回答5:

Within a class you can't reassign this (although it's worth noting that within a struct it's perfectly legal). The question, though, is whether you should. I assume that your goal is to set all field values to a specific state, so as other people have already said you can either have your Reset method return a new instance or you can break out your logic into a Clear() method and call that instead.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!