我是靠谱客的博主 受伤棒球,这篇文章主要介绍C#中this用法系列(二) 通过this修饰符为原始类型扩展方法,现在分享给大家,希望可以做个参考。

定义一个静态类,类中定义静态方法,方法中参数类型前边加上this修饰符,即可实现对参数类型的方法扩展

示例如

复制代码
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
namespace Demo{ // 这里的类必须为静态类 public static class Json {      // 方法为静态方法     // this修饰符后边是string类型,即为string类型扩展出了ToJson方法 public static object ToJson(this string Json) { return Json == null ? null : JsonConvert.DeserializeObject(Json); }      // this修饰符后边类型为object,即为object类型扩展出了ToJson方法 public static string ToJson(this object obj) { var timeConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" }; return JsonConvert.SerializeObject(obj, timeConverter); } public static string ToJson(this object obj, string datetimeformats) { var timeConverter = new IsoDateTimeConverter { DateTimeFormat = datetimeformats }; return JsonConvert.SerializeObject(obj, timeConverter); } public static T ToObject<T>(this string Json) { return Json == null ? default(T) : JsonConvert.DeserializeObject<T>(Json); } public static List<T> ToList<T>(this string Json) { return Json == null ? null : JsonConvert.DeserializeObject<List<T>>(Json); } public static DataTable ToTable(this string Json) { return Json == null ? null : JsonConvert.DeserializeObject<DataTable>(Json); } public static JObject ToJObject(this string Json) { return Json == null ? JObject.Parse("{}") : JObject.Parse(Json.Replace("&nbsp;", "")); } } public class User { public string ID { get; set; } public string Code { get; set; } public string Name { get; set; } } class Program { static void Main(stringtry { List<User> users = new List<User>new User{ID="1",Code="zs",Name="张三"}, new User{ID="2",Code="ls",Name="李四"} }; // List被扩展出了ToJson方法,用于转化字符串 string json = users.ToJson(); // string类型被扩展出了ToJson方法,用于转化对象 object obj = json.ToJson(); // string类型被扩展出了ToList方法,用于转化List users = json.ToList<User>();                     // string类型转化DataTable           DataTable dt=json.ToTable(); } catch (Exception ex) { Console.WriteLine(ex); } finally { Console.ReadLine(); } } } }

以上所述是小编给大家介绍的C#中this用法系列(二) 通过this修饰符为原始类型扩展方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对靠谱客网站的支持!

最后

以上就是受伤棒球最近收集整理的关于C#中this用法系列(二) 通过this修饰符为原始类型扩展方法的全部内容,更多相关C#中this用法系列(二)内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(151)

评论列表共有 0 条评论

立即
投稿
返回
顶部