首页 > 解决方案 > 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);

但我想知道它是否可以以前一种方式实现。

标签: c#propertiesvariable-assignmentassignment-operator

解决方案


它很丑,但它可以满足您的要求;

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;
    }
}

推荐阅读