繁体   English   中英

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

[英]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

那这个呢?

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 作为后台存储

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

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

下面的代码可以帮助你,

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,如果它的 null 将数据分配给 addressinfo 那么你可以更新该值,否则你会得到对象引用错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM