可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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.