-1

私はプロパティDateOfBirthとプロパティを持っていますAge

DateOfBirthDateTimeデータ型であり、Ageデータint型です。

コンストラクター内で人の年齢を計算したいのですが、次のようにしています。

private int CalculateAge(DateTime birthDate, DateTime now)
{
   int age = now.Year - birthDate.Year;
   if (now.Month < birthDate.Month || (now.Month == birthDate.Month && now.Day < birthDate.Day))
   {
      age--;
   }            
   return age;
}

public virtual DateTime? Dob { get; set; }
public virtual int Age { get; set; }

public MyObject()
{
   Age = CalculateAge(Dob, DateTime.Now);
}

コンパイル時に次のエラーが発生します。

... に最適なオーバーロードされたメソッドの一致には、無効な引数があります

「System.DateTime?」から変換できませんか? System.DateTime に

4

9 に答える 9

2

null許容のDateTimeではなくDateTimeを渡す必要があります

Age = CalculateAge((Dob.HasValue ? Dob.Value : DateTime.Now), DateTime.Now);

または受け取り方法を変更する

private int CalculateAge(DateTime? birthDate, DateTime now)

NullReferenceExceptions を回避するために必要なすべてのチェックを適用します。

于 2013-06-06T10:36:18.850 に答える
1

メソッドはパラメーターをCalculateAge受け入れ、それを(nullable )DateTimeに渡します。これらのいずれかを変更するか、にキャストする必要があります。DateTime?DateTimeDateTime

DateTime.Nowさらに、メソッド内で計算できるため、2 番目のパラメーターには実際の理由はありません。

3 番目に、年齢を計算するための SO に関する同様の質問を参照してください: C# で年齢を計算する

于 2013-06-06T10:34:31.280 に答える
1

メソッド宣言を見てください

private int CalculateAge(DateTime birthDate, DateTime now)

そして DateOfBirth 宣言

public virtual DateTime? Dob { get; set; }

null 許容の DateTime プロパティを最初のパラメーターとして使用することはできません。宣言を次のように変更

private int CalculateAge(DateTime? birthDate, DateTime now)

または Dob プロパティから nullability を削除します

public virtual DateTime Dob { get; set; }
于 2013-06-06T10:36:24.240 に答える
0

DateTime をキャストする必要がありますか? そのようにDateTimeに

(DateTime)Dob

しかし、コードのどこかで null 日付の可能性を処理していないのに、そもそも Dob を nullable にする必要があるでしょうか?

于 2013-06-06T10:40:11.607 に答える
0

使用できます

public static int GetAge(DateTime birthDate)
{
DateTime n = DateTime.Now; // To avoid a race condition around midnight
int age = n.Year - birthDate.Year;

if (n.Month < birthDate.Month || (n.Month == birthDate.Month && n.Day < birthDate.Day))
age--;

return age;
}
于 2013-06-06T10:35:54.810 に答える
0
use private int CalculateAge(DateTime? birthDate, DateTime now)

それ以外の

private int CalculateAge(DateTime birthDate, DateTime now)
于 2013-06-06T10:36:21.357 に答える
0

ここで説明するように、TimeSpan を使用して 2 つの日付の差を取得します。

private int CalculateAge(DateTime birthDate, DateTime now)
{
   TimeSpan span = now.Subtract(birthDate);     
   return (int)span.TotalDays / 365;  
}
于 2013-06-06T10:36:22.710 に答える