简体   繁体   中英

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

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...

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM