开发者

How to create C# class instance from a static method return value?

开发者 https://www.devze.com 2023-03-13 18:20 出处:网络
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

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);
}

开发者_JAVA技巧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...


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:

public class MyClass
{
    public MyClass() {}
    public MyClass(XElement data)
    {
        loadXml(this, data);    
    }
    public static MyClass LoadXml(data)
    {
        var output = new MyClass();
        loadXml(output, data);
        return output;
    }
    private static void loadXml(MyClass classToInitialize, XElement data)
    {
        // your loading code goes here
    }
}


You could create a non-public method static MyClass FromXml(XElement data, MyClass instance) which fills the passed-in instance using data. You can then call that from the constructor, passing this as an argument.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号