-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTExtension.cs
112 lines (91 loc) · 2.84 KB
/
TExtension.cs
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace Aya.Extension
{
public static class TExtension
{
#region Null / Empty
public static bool IsNull<T>(this T value)
{
var result = ReferenceEquals(value, null);
return result;
}
public static bool IsNotNull<T>(this T value)
{
var result = !ReferenceEquals(value, null);
return result;
}
public static bool IsEmpty<T>(this T value) where T : struct
{
var result = value.Equals(default(T));
return result;
}
public static bool IsNotEmpty<T>(this T value) where T : struct
{
var result = value.IsEmpty() == false;
return result;
}
public static T? ToNullable<T>(this T value) where T : struct
{
var result = value.IsEmpty() ? null : (T?) value;
return result;
}
#endregion
#region Equal
public static bool EqualsAny<T>(this T value, params T[] values)
{
if (values == null) return false;
for (var i = 0; i < values.Length; i++)
{
var arg = values[i];
if (value.Equals(arg)) return true;
}
return false;
}
public static bool EqualsNone<T>(this T value, params T[] values)
{
var result = value.EqualsAny(values) == false;
return result;
}
#endregion
#region Deep Copy
public static T DeepCopy<T>(this T target)
{
T obj2;
var formatter = new BinaryFormatter();
var serializationStream = new MemoryStream();
try
{
formatter.Serialize(serializationStream, target);
serializationStream.Position = 0L;
obj2 = (T)formatter.Deserialize(serializationStream);
}
finally
{
serializationStream.Close();
}
return obj2;
}
#endregion
#region Flag
public static bool HasFlags<T>(this T value, params T[] flags) where T : struct, IComparable, IFormattable, IConvertible
{
if (!typeof(T).IsEnum) throw new ArgumentException("variable must be an Enum", nameof(value));
foreach (var flag in flags)
{
if (!Enum.IsDefined(typeof(T), flag))
{
return false;
}
var numFlag = Convert.ToUInt64(flag);
if ((Convert.ToUInt64(value) & numFlag) != numFlag)
{
return false;
}
}
return true;
}
#endregion
}
}