如何从静态方法返回值创建 C# 类实例?
我尝试使用 XDocument (XML Linq) 来保存和加载类。为此,我有两种方法:
static MyClass FromXml(XElement data); //calls 0-parameter constructor inside
public XElement ToXml();
像这样的构造函数
public MyClass(XElement data)
{
this = MyClass.FromXml(data);
}
不起作用(说这是只读的)。 这可以以某种方式完成(无需从返回值手动复制每个字段)吗?
或者这个想法本身就是错误的?
将代码从 FromXml
移动到构造函数应该可以工作,但是保存和加载将在两个位置,或者构造函数不会全部集中在一个位置......
I try to use XDocument
(XML Linq) to save and load classes. For this I have two methods:
static MyClass FromXml(XElement data); //calls 0-parameter constructor inside
public XElement ToXml();
A constructor like this
public MyClass(XElement data)
{
this = MyClass.FromXml(data);
}
does not work (says this is read only).
Can this be done somehow (without creating copying each field manually from the returned value)?
Or is the very idea wrong?
Moving the code from FromXml
to constructor should work, but then saving and loading would be in two places or constructors would not be all in one place...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为你不需要一个构造函数;您需要一个返回 MyClass 类型的静态工厂方法。看来您已经使用 FromXml 方法实现了该功能。您始终可以编写复制构造函数如果你真的想要的话,它会接受 MyClass 的另一个实例。
I don't think you want a constructor; you want a static factory method that returns type MyClass. It looks like you already have that with method FromXml. You could always write a copy constructor that takes in another instance of MyClass if you really wanted.
我想你会需要这样的东西:
I think you would need something like this:
您可以创建一个非公共方法
static MyClass FromXml(XElement data, MyClass instance)
,它使用data
填充传入的实例
。然后,您可以从构造函数调用它,并将this
作为参数传递。You could create a non-public method
static MyClass FromXml(XElement data, MyClass instance)
which fills the passed-ininstance
usingdata
. You can then call that from the constructor, passingthis
as an argument.