在构造函数运行之前,可以使用对象初始化语法为属性分配值吗? [英] Can I use Object Initialization Syntax to assign values to properties before the constructor runs?

查看:41
本文介绍了在构造函数运行之前,可以使用对象初始化语法为属性分配值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 System.Xml.Serialization 将对象序列化为XML,这需要我具有无参数的构造函数.

I am serializing objects to XML using System.Xml.Serialization and this requires me to have parameterless constructors.

因此,我尝试使用对象初始化语法为某些属性分配值,然后在将对象序列化为XML之前,根据需要使用构造函数逻辑对这些值进行格式化.

I am therefore trying to use Object Initialization Syntax to assign values to certain properties and then use the constructor logic to format these values as needs be before I serialize the objects to XML.

我的问题是,构造函数在为属性分配它们的值之前运行.下面是一个简化的示例:

My problem is that the constructor runs before the properties are assigned their values. A simplified example is below:

class Program
{
    static void Main(string[] args)
    {
        Foo myFoo = new Foo() { HelloWorld = "Beer", HelloWorldAgain = "More beer" };

        Console.WriteLine(myFoo.HelloWorld);
        Console.WriteLine(myFoo.HelloWorldAgain);

        Console.ReadLine();
    }
}

public class Foo : Bar
{
    public string HelloWorld { get; set; }

    public Foo()
    {
        Console.WriteLine("Foo Was Initialized");
        Console.WriteLine(HelloWorld);
    }
}

public abstract class Bar
{
    public string HelloWorldAgain { get; set; }

    public Bar()
    {
        Console.WriteLine("Bar was initialized");
        Console.WriteLine(HelloWorldAgain);
    }
}

这将导致以下输出:

如您所见,构造函数逻辑将运行,然后为属性分配值.我需要用其他方法来解决这个问题.

As you can see the constructor logic runs, and then the properties are assigned values. I need this to work the other way around.

这可能吗?

推荐答案

序列化要求您具有无参数的构造函数,但不限于您使用那个构造函数.

Serialization requires you to have a parameterless constructor, but does not limit you to that one constructor.

保留no-arg构造函数以进行反序列化,但添加另一个构造函数,该构造函数将使用您的值并在需要在代码中实例化该类时执行所需的初始化.

Keep the no-arg constructor for deserialization, but add another constructor that takes your values and does the required initialization when you need to instantiate the class in code.

对象初始化语法只是构造后设置属性的简写.

Object initialization syntax is just shorthand for setting properties after construction.

这篇关于在构造函数运行之前,可以使用对象初始化语法为属性分配值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆