根据资源库中另一个属性的值更新类属性



我有两个模型类:

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

这将adverseInfo用作后退存储

您可以简单地写入以下班级:

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

在分配值以确保adverseionInfo而非null之前,如果将数据分配给addressInfo,则可以更新该值,否则您将获得对象参考错误。

相关内容

  • 没有找到相关文章

最新更新