我想使用具有隱式運算符的泛型類。問題是使用底層函數。我認爲最好的具體定義我的代碼像DateTime這樣的類型的隱式運算符,沒有像ToShortDateString()這樣的日期時間函數
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
如果日期時間爲空,我需要另一種方法,調用
public AnnotationField<DateTime?> Birthday { get; set; }
myObject.Birthday.Value.Value.ToShortDateString(); // <- Works but is not really usable!
我不認爲你可以做你想做的事,至少不是沒有使用反射和丟失類型的安全。對於可以繼承的T,顯然是可行的。雖然沒有幫助你。 – Rob
或者,如果您不關心類型安全和智能善良,您可以使用動態類型。 – Rob