根据 setter 中另一个 属性 的值更新 class 属性

Update a class property based on another property's value in the setter

我有两个型号类:

public class Person
{
    public int PersonId { get; set; }
    public string Name { get; set; }
    public int AddressId { get; set; }
    public Address AddressInfo { get; set; }
}

public class Address
{
    public int AddressId { get; set; }
    public string streetName { get; set; }
    public string City { get; set; }
    public string State { get; set; }
}

如果 Person.AddressInfo.AddressId 中的任何值得到更新,我如何自动更新 Person.AddressId

您可以简单地将以下内容写入 Person class:

 public int AddressId{
    get{return this.AddressInfo?.AddressId ?? 0;}
    set{this.AddressInfo?.AddressId= value;}
 }

或者更好写:

 public int? AddressId{
    get{return this.AddressInfo?.AddressId;}
    set{this.AddressInfo?.AddressId= value;}
 }

这个呢?

public class Person
{
    public int PersonId { get; set; }
    public string Name { get; set; }
    public int AddressId 
    { 
        get{ return AddressInfo?.AddressId ?? 0 } 
        set{ AddressInfo?.AddressId = value; }
    }
    public Address AddressInfo { get; set; }
}

public class Address
{
    public int AddressId { get; set; }
    public string streetName { get; set; }
    public string City { get; set; }
    public string State { get; set; }
}

这使用 AddressInfo 作为后台存储

下面的代码可以帮助你,

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

namespace ConsoleApplication5
{
    class Program
    {
        static void Main(string[] args)
        {
            Address test = new Address();
            test.AddressId = 0;
            test.City = "xyzzzzzzzzzzzzzzz";
            test.streetName = "xyz";
            test.State = "xyzzzzzzzzzzzzzzzxxxxxxxxxxxxxxxxxxx";

            Person ptest = new Person
            {
                PersonId = 1,
                Name = "test1",
                AddressInfo = test,
                AddressId = 5,
            };
        }
    }

    public class Address
    {
        public int AddressId { get; set; }
        public string streetName { get; set; }
        public string City { get; set; }
        public string State { get; set; }
    }
    public class Person
    {
        public int PersonId { get; set; }
        public string Name { get; set; }
        public int AddressId { 

            get{ return AddressInfo != null ? AddressInfo.AddressId : 0;}
            set { AddressInfo.AddressId = value; }
    }
        public Address AddressInfo { get; set; }
    }
}

在给addressid赋值前确保addressinfo不为null,如果addressinfo为null则可以更新该值,否则会出现对象引用错误。