2

I want to use the generic class with implicit operators. The problem is to use underlaying functions. I think the best describtion is my code

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;
    }
}

Using:

public AnnotationField<DateTime> Birthday { get; set; }

myObject.Birthday = new DateTime(1986, 7, 2); // <- Works
myObject.Birthday.ToShortDateString();  // <- Compiler-Error !
myObject.Birthday.Value.ToShortDateString();  // <- Works

If the DateTime is nullable I need another method-calling

public AnnotationField<DateTime?> Birthday { get; set; }

myObject.Birthday.Value.Value.ToShortDateString(); // <- Works but is not really usable!
4

2 に答える 2

0

タイプに拡張メソッドを追加します。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();
于 2013-07-05T09:54:20.417 に答える