How to make class in C#, that can be cast to DateTime?

£可爱£侵袭症+ 提交于 2019-12-01 02:45:44
Adam Houldsworth

What you appear to be after is inheritance, being able to "store" a derived class instance in a variable of the base type like so:

Stream s = new FileStream();

The fact that it is a FileStream under the hood is not lost just because you are pointing to it with the Stream goggles on.

DateTime is a struct, and struct inheritance is not supported - so this is not possible.

An alternative is the explicit keyword for user-defined conversions (syntactically looking like casts). This allows you to at least interchange between your class and DateTime with more sugar.

This could look like:

class MyDateTime
{
    private DateTime _inner;

    public static explicit operator DateTime(MyDateTime mdt)
    {
        return mdt._inner;
    }
}

You can do the same with the counterpart implicit keyword:

public static implicit operator DateTime(MyDateTime mdt)
{
    return mdt._inner;
}

That then lets you do the "casting" implicitly:

DateTime date = new MyDateTime();

Another alternative is to wrap DateTime with your own adapter class that internally uses a DateTime and then inherit from this class to create MyDateTime. Then instead of using DateTime in your code base, you use this adapter class.

I've seen similar things with SmartDateTime style classes where the DateTime has a better understanding of nulls and if it was set.

You could use

class MyDateTime
{
    public static explicit operator DateTime(MyDateTime dt)
    {
        return new DateTime(); // Convert dt here            
    }
}
Brian

Instead of a direct cast, I would create an extension method that performs the required steps to complete the conversion. Some sort of conversion is necessary, because DateTime can't be inherited from, so a direct cast will be impossible.

public static class DateTimeExtensions
{
    public static MyDateTime ToMyDateTime(this DateTime dt)
    {
        //conversion logic
        return myDataTime;
    }
    public static DateTime ToDateTime(this MyDateTime mdt)
    {
        //conversion logic
        return dateTime;
    }
}

In this way, you would use the code like so:

DateTime dt = mdt.ToDateTime();

or

MyDateTime mdt = dt.ToMyDateTime();

You'd need to write an explicit cast operator on your MyDateTime class that calls into one of the constructors on Datetime. Here's an example.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!