Update a class property based on another Property

2019-09-15 05:39发布

问题:

I'm having two model Classes

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

If any value gets update in Person.AddressInfo.AddressId, update the Person.AddressId automatically. Kindly assist me how to update this in C#.

回答1:

what about this?

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

This uses the AddressInfo as the back storage



回答2:

You could simply write following into the Person class:

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

Or better to write:

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


回答3:

below code can help you out,

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

Before assigning value to addressid ensure that addressinfo not null, if its null assign data to addressinfo then you can able to update the value, otherwise you will get object reference error.