C# 原始类型扩展方法

例如:给 DateTime 扩展两个转换成毫秒数和从毫秒数转换成 DateTime 的方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
using UnityEngine;
using System.Collections;
using System;

public class Test : MonoBehaviour
{
void Start()
{
DateTime date = DateTime.Now;
Debug.Log("Now = " + date);
long milliseconds = date.DateTimeToMilliseconds();
Debug.Log("Milliseconds = " + milliseconds);
date = date.MillisecondsToDateTime(milliseconds + 1000);
Debug.Log("date = " + date);
}
}

public static class DateTimeExtension
{
/// <summary>
/// 将当前DateTime转换成毫秒数
/// </summary>
public static long DateTimeToMilliseconds(this DateTime date)
{
DateTime date_1970 = new DateTime(1970, 1, 1);
TimeSpan span = date - date_1970;
return Convert.ToInt64(span.TotalMilliseconds);
}

/// <summary>
/// 将给定的毫秒数转换成DateTime
/// </summary>
public static DateTime MillisecondsToDateTime(this DateTime data, long milliseconds)
{
DateTime date_1970 = new DateTime(1970, 1, 1);
return date_1970.AddMilliseconds(milliseconds);
}
}