网站建设公司宣传词,无货电商怎么入门,酒店网站建设的需求分析报告,wordpress qq登录插件我们知道#xff0c;在c#中#xff0c;如果两个类型没有继承关系 #xff0c;是不能相互值赋的#xff0c;但有两个关键字implicit和explicit#xff0c;可以让 Date date DateTime.Now这样的赋值成为可能。注#xff1a;c#是没有Date类型的#xff0c;但DateTime有Dat… 我们知道在c#中如果两个类型没有继承关系 是不能相互值赋的但有两个关键字implicit和explicit可以让 Date date DateTime.Now这样的赋值成为可能。注c#是没有Date类型的但DateTime有Date属性 DateTime.Date但这个属性本质上是个DateTime类型只不过时间是00:00:00using System;
using static System.Console;namespace KeyWordsDemo
{class ImplicitAndExplicitDemo : IDemo{public void Run(){//把DateTime赋值 给DateDate date DateTime.Parse(2030-01-01 12:12:12);WriteLine($Date:{date});WriteLine($Year:{date.Year});WriteLine($Month:{date.Month});WriteLine($Day:{date.Day});//把Date转成DateTime类型var datetime (DateTime)date;WriteLine($DateTime:{datetime});}public struct Date{private DateTime _value;public int Year{get{return _value.Year;}}public int Month{get{return _value.Month;}}public int Day{get{return _value.Day;}}public static implicit operator Date(DateTime dateTime){var date new Date();date._value dateTime;return date;}public static explicit operator DateTime(Date date){return date._value.Date;}public override string ToString(){return _value.ToString(yyyy/MM/dd);}}}
}
这里的Date只是简单封装可根据自己的需求进行精确处理。Date date DateTime.Parse(2030-01-01 12:12:12);会调用public static implicit operator Date(DateTime dateTime)方法。var datetime (DateTime)date;会调用public static explicit operator DateTime(Date date)方法。implicit和explicit为我们又提供了一种“打通”两种类型的方式。