DateTime等类型上的隐式运算符,而没有ToShortDateString()等日期时间函数
本文关键字:ToShortDateString 日期 函数 时间 类型 DateTime 运算符 | 更新日期: 2023-09-27 18:21:04
我想使用带有隐式运算符的泛型类。问题在于使用参考底图函数。我认为最好的描述是我的代码
public class AnnotationField<T>
{
public T Value { get; set; }
public bool IsNullValue { get; set; }
public CompareTypes CompareType { get; set; }
public static implicit operator T(AnnotationField<T> temp)
{
return temp.Value;
}
public static implicit operator AnnotationField<T>(T temp)
{
Type correctType = Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T);
AnnotationField<T> annotationField = new AnnotationField<T> {};
annotationField.Value = (T)Convert.ChangeType(temp, correctType);
return annotationField;
}
}
使用:
public AnnotationField<DateTime> Birthday { get; set; }
myObject.Birthday = new DateTime(1986, 7, 2); // <- Works
myObject.Birthday.ToShortDateString(); // <- Compiler-Error !
myObject.Birthday.Value.ToShortDateString(); // <- Works
如果DateTime可以为null,我需要另一个调用的方法
public AnnotationField<DateTime?> Birthday { get; set; }
myObject.Birthday.Value.Value.ToShortDateString(); // <- Works but is not really usable!
在AnnotationField<DateTime?>
类型上添加一个扩展方法:
public static class Extensions
{
public static string ToShortDateString(this AnnotationField<DateTime?> item)
{
return item.Value.Value.ToShortDateString();
}
}
有了这个,你就可以打电话给:
public AnnotationField<DateTime?> Birthday { get; set; }
myObject.Birthday.ToShortDateString();
据我所知,没有办法做到这一点。编译器的问题是,在AnnotationField<DateTime>
上调用的是ToShortDateString
方法,而不是DateTime
,因为隐式的东西只发生在运行时,而不是编译时。
然而,如果struct
支持继承,那么就可以从DateTime
派生,目前实现这一点的唯一方法是从AnnotationField<DateTime>
派生并引入这些方法并委托调用,或者更抽象的方法是使用扩展方法(如前所述)。