C# default value in constructor same as two constructors for serialization

点点圈 提交于 2019-12-19 05:57:29

问题


When I provide a constructor with a default value

  public MyClass(string description = null) { .... }

is this equivalent to

  public MyClass() { .... }
  public MyClass(string description) { .... }

in terms of Serialization. In other words, is a default constructor available? Practically it is, but will I face some issues when I use serialization?


回答1:


No. It unfortunately is not a default constructor.

When you write:

public MyClass(string description = null) { .... }

You're actually making a constructor that accepts a string parameter, but has an attribute marking the default value for that attribute. This is different than having a default constructor on the class.




回答2:


Yes, you will have problems in that case.

I've tried to call a constructor described by you via reflection, and it thrown TargetInvokationException: (Argument count mismatch).



来源:https://stackoverflow.com/questions/8012558/c-sharp-default-value-in-constructor-same-as-two-constructors-for-serialization

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