我想使用带有隐式运算符的泛型类。问题是使用底层函数。我认为最好的描述是我的代码
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 可以为空,我需要另一个方法调用
public AnnotationField<DateTime?> Birthday { get; set; }
myObject.Birthday.Value.Value.ToShortDateString(); // <- Works but is not really usable!
最佳答案
添加 extension method在 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();
关于c# - 不带日期时间函数(如 ToShortDateString())的 DateTime 等类型的隐式运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17485905/