C# 重载在 class 中找到的对象的 属性

C# overloading a property of an object found in a class

我想知道是否有一种方法可以在不重载后者的情况下从 class 覆盖 属性。

例如,使用新的 C# 版本,我想知道是否可以通过任何方式从 Address 覆盖 属性 Street class。我想在调用的 class Person.[=15= 中添加 Street 属性 的一些数据注释]

  public class Address
  {
        [Display(Name = "Street")]
        public string Street { get; set; }
  
        public string City { get; set; }
  }

    public class Person
    {
        public string Firstname { get; set; }
        public string Lastname { get; set; }

        public Address Address { get; set; }

        [Display(Name="Street with street number")]
        public new Address.Street  { get;set; } // new or override or anything to access at the Street property in the called class
    }

    class Program
    {
        public Person Person { get; set; }

        static void Main(string[] args)
        {
            var person = new Person() { Firstname = "John", Lastname = "Doe" };
            person.Address = new Address() {Street = "2 mainstreet" , City = "Chicago"};

            Console.WriteLine($"{person.Firstname} {person.Lastname} - {person.Address.Street}, {person.Address.City}");
        } 
    }

我不知道你的情况下继承的用法,但你可以做到这一点 通过更改 getter/setter:

public class Person
    {
        public string Firstname { get; set; }
        public string Lastname { get; set; }

        public Address Address { get; set; }

        [Display(Name="Street with street number")]
        public string Street  { get{return this.Address.Street; }
                               set{this.Address.Street = value;} }
    }