gpt4 book ai didi

c# - 如何在 C# 中创建可以转换为 DateTime 的类?

转载 作者:可可西里 更新时间:2023-11-01 08:00:42 25 4
gpt4 key购买 nike

我如何创建可以转换为 DateTime 的类。但是当它打包时,我需要上课。例如:

object date1 = new MyDateTime();
DateTime date2 = (DateTime)date1;

我直接需要这个工作示例。

我知道该怎么做,但我的方法无需打包也能奏效。我不确定是否有办法做到这一点。

请帮忙。

附言。我需要直接将对象转换为 DateTime。所以,MyDateTime 之前必须打包。 Explicit 效果很好,但如果您有打包的对象,它就无济于事。而且它必须使用像

这样的普通转换来转换
(DateTime) (object) MyDateTime

最佳答案

您似乎追求的是继承,能够将派生类实例“存储”在基类型的变量中,如下所示:

Stream s = new FileStream();

它是一个 FileStream 的事实并没有因为你戴着 Stream 护目镜指向它而丢失。

DateTime 是一个 struct,不支持 struct 继承 - 所以这 可能。

另一种选择user-defined conversionsexplicit 关键字(在语法上看起来 像转换)。这使您至少可以在类和 DateTime 之间交换更多糖分。

这看起来像:

class MyDateTime
{
private DateTime _inner;

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

您可以对对应的 implicit 关键字执行相同的操作:

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

然后你就可以隐式地进行“转换”:

DateTime date = new MyDateTime();

另一种选择是用你自己的内部使用DateTime的适配器类包装DateTime,然后继承这个类来创建我的日期时间。然后,您可以使用此适配器类,而不是在您的代码库中使用 DateTime

我在 SmartDateTime 样式类中看到过类似的情况,其中 DateTime 可以更好地理解 null 以及它是否已设置。

关于c# - 如何在 C# 中创建可以转换为 DateTime 的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10121630/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com