c# - C# - 通过将值直接分配给实例来为对象的属性赋值
问题描述
考虑以下类:
class Person
{
public string Name { get; set; }
public DateTime Birth { get; set; }
public bool IsMaried { get; set; }
public override string ToString()
=> $"{Name} was born on {Birth.ToShortDateString()} and is{(IsMaried ? "" : " not")} maried";
}
我怎么能写出这样的代码:
var person = new Person();
person += "Erick"; // string should be assigned to the Name property of the instance.
person += new DateTime(1998, 10, 28); // DateTime object should be assigned to Birth property of the instance.
person += true; // bool should be assigned to IsMaried property of the instance.
起初,运算符重载似乎是问题所在,但我没有成功。
我知道有一种解决方法,例如:
public void Set<T>(PersonField field, T value);
但我想知道它是否可以以前一种方式实现。
解决方案
它很丑,但它可以满足您的要求;
void Main()
{
var person = new Person();
person += "Erick"; // string should be assigned to the Name property of the instance.
person += new DateTime(1998, 10, 28); // DateTime object should be assigned to Birth property of the instance.
person += true; // bool should be assigned to IsMaried property of the instance.
Console.WriteLine(person);
//Output
//Erick was born on 28.10.1998 and is maried
}
class Person
{
public string Name { get; set; }
public DateTime Birth { get; set; }
public bool IsMaried { get; set; }
public override string ToString()
=> $"{Name} was born on {Birth.ToShortDateString()} and is{(IsMaried ? "" : " not")} maried";
public static Person operator +(Person p, string n)
{
p.Name=n;
return p;
}
public static Person operator +(Person p, DateTime b)
{
p.Birth=b;
return p;
}
public static Person operator +(Person p, bool b)
{
p.IsMaried = b;
return p;
}
}
推荐阅读
- python - 在 Keras 嵌入层中获取一个热向量
- autodesk-forge - 使用 Autodesk Forge 查看器时,是否可以按需加载模型的不同部分(不是所有部分)
- python - 如何使用有时包含 np.nan 的其他列的字符串填充 df 列,遍历 elifs 以返回适当的组合?
- node.js - Nodejs sequelize hasMany 问题
- javascript - Vue如何在密码输入中显示字数限制?
- r - 对所有变量运行 svymean
- azure-pipelines - 为什么在 ADF 中不进行克隆就无法重命名管道?
- python-3.x - 如何使用python子进程并行运行命令列表列表
- c++ - 如何在 C++ 中实现 OOBE 完成通知?
- function - 我可以为 Lua shell 提示符运行一个函数吗?