Why does System.Convert has ToDateTime that accept

2020-08-13 05:25发布

问题:

//
// Summary:
//     Returns the specified System.DateTime object; no actual conversion is performed.
//
// Parameters:
//   value:
//     A date and time value.
//
// Returns:
//     value is returned unchanged.
public static DateTime ToDateTime(DateTime value);

Why does System.Convert has ToDateTime that accepts DateTime ?

The method documentation states the value remain unchanged.

回答1:

Convention, predictability and because the IConvertable defines the method ToDateTime.

My believe is that under the covers System.Convert simply runs through all the combinations of the IConvertable classes.



回答2:

The actual code is indeed:

public static DateTime ToDateTime(DateTime value)
{
  return value;
}

This confirms the value will be unmodified. There are a lot of convert methods. I think it is there just because it should accept all primitive objects in the signatures.

I.e. when using reflection, if would be unexpected if a convert from a DateTime to DateTime is not supported.