提问人:Erick Ruh Cardozo 提问时间:7/9/2020 最后编辑:phoErick Ruh Cardozo 更新时间:7/11/2020 访问量:2927
C# - 通过将对象的属性直接分配给实例来为对象的属性赋值 [已关闭]
C# - Assign value to object's property by assigning them directly to the instance [closed]
问:
考虑以下类:
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);
但我想知道它是否能以前一种方式实现。
答:
0赞
Mike Eber
7/9/2020
#1
你的代码应该是这样的。
Person person = new Person();
person.Name = "Erick";
person.Birth = DateTime.Parse("10-28-1998");
person.IsMarried = true;
Debug.WriteLine("Person ToString: " + person.ToString());
评论
1赞
Falco Alexander
7/9/2020
这不是问题的答案!
0赞
Mike Eber
7/9/2020
Person 是一个对象类。你不能通过执行 += 将数据分配给类,这仅适用于 int、string 等变量。必须使用 Objects 属性分配数据。
1赞
Falco Alexander
7/9/2020
这不是真的!该问题甚至包含如何做(重载运算符)。检查事件或委托,它们具有内置和运算符,当然还与类/引用类型一起使用。+
-
0赞
Mike Eber
7/9/2020
例如,在执行“person += true”时,您将得到“运算符'+='不能应用于'Person'和'bool'类型的操作数”;C# 不知道您指的是哪个属性。你为什么要这样做?
0赞
Falco Alexander
7/10/2020
请看我对“如何”的回答,而不是“为什么”
3赞
Falco Alexander
7/9/2020
#2
它很丑陋,但它符合您的要求;
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;
}
}
评论
1赞
Chris Cudmore
7/9/2020
然后我们进入真正的问题:为什么这是可取的?如果这是一个学术黑客练习,那就好了。
1赞
Falco Alexander
7/9/2020
没错,但所有这些真实的评论都已经在问题下面了...... ;)
0赞
Mike Eber
7/10/2020
哎呀,这太可怕了。并且有一个问题,如果你有多个变量作为属性怎么办。即两个字符串 FirstName LastName。
1赞
7/10/2020
你应该为提出这样的解决方案而感到羞耻:)
1赞
Falco Alexander
7/10/2020
:)我还年轻,需要积分......
评论
Person
public static Person operator+(Person person, object value)