如何使C#中的类可以转换为DateTime? [英] How to make class in C#, that can be cast to DateTime?
问题描述
如何使类可以转换为DateTime。但是,当我打包的时候,我需要投下我的班级。例如:
object date1 = new MyDateTime();
DateTime date2 =(DateTime)date1;
我需要直接这个工作示例。
我知道该怎么做,但是我的方式会在没有包装的情况下工作。我不知道有没有办法。
请帮忙。
PS。我需要直接将对象转换为DateTime。所以,MyDateTime必须先包装。显式效果很好,但是如果你打包对象没有帮助。而且它必须使用普通铸造,如
(DateTime)(对象)MyDateTime
你似乎是继承,能够存储派生类实例基本类型的变量如下所示:
Stream s = new FileStream();
事实上,它是一个 FileStream
<$ c $ c> DateTime
是一个 struct
,而 struct
继承不受支持 - 所以这是
DateTime
之间交换更多糖。 http://msdn.microsoft.com/en-us/library/xhbhezf4( v = vs.71).aspx
这可能如下所示:
class MyDateTime
{
private DateTime _inner;
public static显式运算符DateTime(MyDateTime mdt)
{
return mdt._inner;
}
}
你可以和对方一样做 implicit
关键字:
public static implicit operator DateTime(MyDateTime mdt)
{
return mdt._inner;
}
那么你可以隐式地进行转换:
DateTime date = new MyDateTime();
另一种替代方法是将 DateTime
与您自己的适配器类,内部使用一个
DateTime
,然后继承此类创建 MyDateTime
。然后在代码库中使用 DateTime
,您可以使用此适配器类。
我看到过类似的东西使用 SmartDateTime
样式类,其中 DateTime
更好地了解null,如果已设置。
How can I make class, that can be cast to DateTime. But I need to cast my class, when it packed. For example:
object date1 = new MyDateTime();
DateTime date2 = (DateTime)date1;
I need directly this working example.
I know how to do it, but my way will work without packing. I'm not sure is there way to do it.
Please, help.
PS. I need cast directly object to DateTime. So, MyDateTime have to be packed before. Explicit works well, but it doesn't help if you have packed object. And it have to cast just using ordinary casting like
(DateTime) (object) MyDateTime
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.
http://msdn.microsoft.com/en-us/library/xhbhezf4(v=vs.71).aspx
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.
这篇关于如何使C#中的类可以转换为DateTime?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!