简体   繁体   English

如何从静态方法返回值创建C#类实例?

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

I try to use XDocument (XML Linq) to save and load classes. 我尝试使用XDocument (XML Linq)保存和加载类。 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... 将代码从FromXml移至构造函数应该可以,但是保存和加载将放在两个地方,或者构造函数不会全部放在一个地方...

I don't think you want a constructor; 我认为您不需要构造函数; you want a static factory method that returns type MyClass. 您需要一个返回类型为MyClass的静态工厂方法 It looks like you already have that with method FromXml. 看起来您已经可以使用FromXml方法了。 You could always write a copy constructor that takes in another instance of MyClass if you really wanted. 如果确实需要,您总是可以编写一个复制构造函数 ,该构造函数接受MyClass的另一个实例。

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 . 您可以创建一个非公共方法static MyClass FromXml(XElement data, MyClass instance) ,该方法使用data填充传入的instance You can then call that from the constructor, passing this as an argument. 然后,您可以从构造函数中调用它,并将this作为参数传递。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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