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 回答
0

据我所知,没有办法做到这一点。编译器看到的问题不是被调用的方法ToShortDateString,因为隐含的东西只发生在运行时,而不是编译时。AnnotationField<DateTime>DateTime

如果struct支持继承,您可以从 派生DateTime,但是,您可以完成此任务的唯一方法是派生AnnotationField<DateTime>并引入这些方法并委托调用,或者更抽象的方法是使用扩展方法(如已经建议)。

于 2013-07-05T10:16:05.610 回答