简体   繁体   English

我可以使用对象初始化语法在构造函数运行之前为属性赋值吗?

[英]Can I use Object Initialization Syntax to assign values to properties before the constructor runs?

I am serializing objects to XML using System.Xml.Serialization and this requires me to have parameterless constructors. 我使用System.Xml.Serialization将对象序列化为XML,这要求我System.Xml.Serialization参数构造函数。

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. 因此,我尝试使用对象初始化语法为某些属性赋值,然后在将对象序列化为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);
    }
}

This results in the following output: 这导致以下输出:

产量

As you can see the constructor logic runs, and then the properties are assigned values. 如您所见,构造函数逻辑运行,然后为属性分配值。 I need this to work the other way around. 我需要这个以相反的方式工作。

Is this possible? 这可能吗?

Serialization requires you to have a parameterless constructor, but does not limit you to that one constructor. 序列化要求您具有无参数构造函数,但不限制您使用该构造函数。

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. 保留no-arg构造函数以进行反序列化,但添加另一个获取值的构造函数,并在需要在代码中实例化类时执行所需的初始化。

Object initialization syntax is just shorthand for setting properties after construction. 对象初始化语法只是构造后设置属性的简写。

No. Object initialization syntax is just a shortcut. 不。对象初始化语法只是一种快捷方式。 When you write: 当你写:

Foo foo = new Foo { HelloWorld  = "Beer" };

The compiler just rewrites this to something very close to what happens if you write: 编译器只是将其重写为非常接近于写入时发生的事情:

Foo foo = new Foo();
foo.HelloWorld  = "Beer";

If the parameters are required in order for your object to exist, you should put them as arguments in the constructor. 如果为了使对象存在而需要参数,则应将它们作为参数放在构造函数中。

No it's not possible, cause in order to be able to initialize a property of the object, object has already exist. 不,它不可能,因为为了能够初始化对象的属性,对象已经存在。 It's existance is guranteed by ctor running before all other stuff. ctor 所有其他东西之前运行是有保障的。

If we are talking about "not running default constructor", like a conceptual question. 如果我们在讨论“不运行默认构造函数”,就像一个概念性问题。 You can do that by using a static property. 可以使用static属性完成此操作。 In that case Foo() will not be called. 在那种情况下,不会调用Foo()。 But it's naturally out of the current question subject. 但它自然不属于当前的问题主题。

Arguably, the syntax is deceptive. 可以说,语法具有欺骗性。 What is happening here? 这里发生了什么?

var myFoo = new Foo();
myFoo.HelloWorld = "Beer";
myFoo.HelloWorldAgain = "MoreBeer";

That's it, I'm afraid. 就是这样,我很害怕。 It's simply not possible to initialise properties before the constructor has run. 在构造函数运行之前 ,根本无法初始化属性。 The constructor is the first thing that 'happens' after memory for the object is allocated and default values are assigned to fields. 构造函数是在分配对象的内存并将默认值分配给字段后“发生”的第一件事。

BTW, you don't need the parens using the object initialisation syntax. 顺便说一句,您不需要使用对象初始化语法的parens。 This would be just as good (but even more deceptive): 这将是同样好的(但更具欺骗性):

var myFoo = new Foo { HelloWorld = "Beer", HelloWorldAgain = "MoreBeer" };

Looking at your question, it looks like what you're trying to do (modify the properties before serialisation) doesn't belong in the constructor. 看看你的问题,看起来你正在尝试做什么(在序列化之前修改属性)不属于构造函数。

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

相关问题 我可以在创建对象之前计算属性吗? 在构造函数中? - Can I count properties before I create an object? In the constructor? 我可以将构造函数逻辑与对象初始化程序语法一起使用吗? - Can I use constructor logic with object initializer syntax? 我可以在对象的 New() 构造函数中声明一个委托吗? 还是带初始化参数? - Can I declare a delegate in an Object's New() constructor? Or with initialization parameters? 通过ID将值分配给对象属性 - Assign Values to object properties by Id .net 6、服务初始化在值的配置绑定之前,如何将参数传递给构造函数? - In .net 6, how do I pass the parameter to the constructor when the service initialization comes before the configuration binding of values? 如何在C#中一次分配多个对象属性? - How can I assign multiple object properties at once in C#? 为什么我不能在构造函数中分配一个lambda语法只读属性? - Why can't I assign to an lambda-syntax read-only property in the constructor? 在C#中,对象初始化语法是否在赋值之前发生? - In c#, does object initialization syntax happen before assignment? 将多属性的值分配给对象 - Assign values on multi-properties to a object 在 C# 中动态分配对象属性和值 - Dynamically assign object properties and values in c#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM