-
Notifications
You must be signed in to change notification settings - Fork 0
/
Common.cs
113 lines (101 loc) · 3.31 KB
/
Common.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
113
using Newtonsoft.Json;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics.SymbolStore;
using System.Text;
namespace NetPro.RedisManager
{
internal static class Common
{
/// <summary>
/// 反序列化为实体
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="serializedObject"></param>
/// <returns></returns>
public static T Deserialize<T>(byte[] serializedObject)
{
if (serializedObject == null)
return default(T);
var jsonString = Encoding.UTF8.GetString(serializedObject);
return JsonConvert.DeserializeObject<T>(jsonString);
}
/// <summary>
/// 反序列化为实体
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value"></param>
/// <returns></returns>
public static T ConvertObj<T>(string value)
{
value = value.TrimStart('\"').TrimEnd('\"');
if (typeof(T) == typeof(string) || typeof(T).IsValueType)
{
return (T)Convert.ChangeType(value, typeof(T));
}
return JsonConvert.DeserializeObject<T>(value);
}
/// <summary>
/// 序列化为字节
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public static byte[] Serialize(object item)
{
var jsonString = JsonConvert.SerializeObject(item);
jsonString = jsonString.TrimStart('\"').TrimEnd('\"');
return Encoding.UTF8.GetBytes(jsonString);
}
/// <summary>
/// 序列化为字符串
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="item"></param>
/// <returns></returns>
public static string SerializeToString<T>(T item)
{
if (typeof(T) == typeof(string) || typeof(T).IsValueType)
{
return Convert.ToString(item);
}
var jsonString = JsonConvert.SerializeObject(item);
return jsonString;
}
public static void CheckAndProcess(ref string key, ref int expiredTime)
{
//TODO 检查key规则
}
public static string CheckAndProcess(ref string key)
{
return key;
//TODO 检查key规则
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="values"></param>
/// <returns></returns>
public static List<T> ConvetList<T>(RedisValue[] values)
{
List<T> result = new List<T>();
foreach (var item in values)
{
var model = ConvertObj<T>(item);
result.Add(model);
}
return result;
}
public static object GetDefault(this Type type)
{
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
var valueProperty = type.GetProperty("Value");
type = valueProperty.PropertyType;
}
return type.IsValueType ? Activator.CreateInstance(type) : null;
}
}
}