您似乎追求的是继承,能够将派生类实例“存储”在基类型的变量中,如下所示:
Stream s = new FileStream();
事实上,它是一个FileStream
引擎盖下的内容不会仅仅因为您用Stream
护目镜。
DateTime
is a struct
, and struct
不支持继承 - 所以这是not可能的。
替代 is the explicit
关键字为用户定义的转换 https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/user-defined-conversion-operators(语法上looking就像演员表一样)。这至少可以让你在你的班级和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
然后继承这个类来创建MyDateTime
。然后而不是使用DateTime
在您的代码库中,您使用此适配器类。
我见过类似的事情SmartDateTime
风格类,其中DateTime
对空值以及是否已设置有更好的理解。