【问题标题】:Can we compute the value of a class property based upon another value of another property of the same class?我们可以根据同一类的另一个属性的另一个值来计算一个类属性的值吗?
【发布时间】:2018-09-23 01:27:58
【问题描述】:

我有一个名为Person 的类,它具有Name、DateOfBirth 和Age 的属性。 Name 和 DateOfBirth 在创建类实例时提供,但我希望在创建类实例后立即自动计算 Age 属性。我知道如何使用 Parametrized Constructor 来做到这一点,但是当我试图了解属性的强大功能时,我尝试了以下程序,但它没有给出预期的输出。

using System;

namespace Property
{
    class Person
    {
        #region private varaibles
        private int _age;
        #endregion

        #region properties
        public string Name { get; set; }
        public DateTime DateOfBirth { get; set; }
        public int Age
        {
            get { return _age; }
            set { _age = (DateTime.Now - DateOfBirth).Days / 365; }
        }
        #endregion properties
    }

    class Program
    {
        static void Main(string[] args)
        {
            Person P = new Person() { Name = "Merin Nakarmi", DateOfBirth = new DateTime(1990, 1, 12) };
            Console.WriteLine("{0}, whose Date Of Birth is {1} is {2} years old!", P.Name, P.DateOfBirth, P.Age);    
        }
    }
}

我得到的输出是

我预计年龄是 28 岁。请帮助。

【问题讨论】:

  • 是的,您需要一个只读的Age 属性,因为大家都注意到了。但是您的代码中还有另一个问题,您的 Age 属性设置器没有从分配的右侧设置属性;我很惊讶它符合要求。我不知何故怀疑,如果您在 WriteLine 之前将 5 分配给 Age 说:P.Age=5;,那么 Age 属性将从 DateOfBirth 分配,您可能已经看到 28 并且非常困惑。属性设置器始终使用 value 关键字。
  • 附带说明,请记住,并非每年都是 365 天,因此如果您想要准确的年龄,您应该考虑闰年。你可以找到解决方案here。

标签: c# properties


【解决方案1】:

看来您需要一个只读的年龄,如果是这种情况,您不需要在 Age 属性中设置任何内容,只需执行以下操作:

    public int Age
    {
        get { 
               return DateTime.Now.Year - DateOfBirth.Year;
            }
    }

您可能还想看看here 并阅读更多关于属性的信息。
顺便说一句,@John 也指出了关于年龄的正确计算(意味着考虑到闰年,你可能想看看here)

【讨论】:

  • 这应该为你做
  • @Breeze 我可以从您的代码中得出结论,您的生日是 1 月 1 日吗?
  • @John:我知道你的意思。此处的目的是仅展示有关属性的想法。我想让它尽可能简单。
  • 我知道 :) 我只是在迂腐。
  • 我添加了一条注释以解决您正确正确的问题;)
【解决方案2】:

您试图在不设置的情况下读取该属性。所以你可以在代码中做这两件事,比如

get { return ((DateTime.Now - DateOfBirth).Days / 365); }

【讨论】:

    猜你喜欢
    • 2018-04-04
    • 1970-01-01
    • 2017-11-24
    • 1970-01-01
    • 1970-01-01
    • 2020-10-13
    • 1970-01-01
    • 1970-01-01
    • 2023-01-06
    相关资源
    最近更新 更多