c# - 带有表达式的对象初始化器
问题描述
是否可以初始化这样的对象?
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的属性可能很多。
如果不可能,请告知可能的设计原因。
解决方案
我同意 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"
);
}
推荐阅读
- vue.js - 根据条件导入 VueJs 组件
- sql-server - 浏览我部署的多维数据集时测量不显示任何数据行
- c# - 实体框架问题:“ef6.exe - 无法启动此应用程序”
- javascript - 线性渐变背景悬停效果不是从元素边框的开头开始
- c++ - C++20 模块是否与其他语言相似?
- html - 带有标记的文本的 XPath 字符串连接
- javascript - Blazor - 从 C# 类调用 JavaScript
- windows - 为什么按向上箭头不能在嵌套进程中获取上一个命令
- jquery - 将 jQuery 活动类添加到特定 url 页面加载的菜单
- javascript - 在反应路由器中引用组件时元素类型无效