首页 > 解决方案 > 带有表达式的对象初始化器

问题描述

是否可以初始化这样的对象?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApp3
{
    class Student
    {
        public bool IsStudent { get; set; }
        public int Age { get; set; }
        public string Name { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            /*
            ************Concise but not complied***********
            var student = GetDefault()
            {
                Age = 18,
                Name = "Nick"
            };
            */

            var student = GetDefault();
            student.Age = 18;
            student.Name = "Nick";


            Student GetDefault()
            {
                var stu = new Student()
                {
                    IsStudent = true
                };

                return stu;
            }
        }
    }
}

我认为重复的“学生”。是多余的。

我要说的是一种可能的C#语法糖,而不是对象初始化解决方案。Student的属性可能很多。

如果不可能,请告知可能的设计原因。

标签: c#

解决方案


我同意 HimBromBeere 的说法。如果您真的想要语法接近您所描述的,您可以执行以下操作。话虽如此,显然这现在改变了方法的含义,并且可以说这在我看来并不是一个很好的“风格”......但它确实实现了接近你所要求的语法:

public class Student
{
    public bool IsStudent { get; set; }
    public int Age { get; set; }
    public string Name { get; set; }
}

public static void Main(string[] args)
{
    Student GetDefault(params Action<Student>[] modifiers)
    {
        var stu = new Student
        {
            IsStudent = true
        };

        if (modifiers != null)
        {
            foreach (var modifier in modifiers)
            {
                modifier(stu);
            }
        }

        return stu;
    }

    var student = GetDefault(
        s => s.Age = 18,
        s => s.Name = "Nick"
    );
}

推荐阅读