如何创建类型的扩展方法

编程入门 行业动态 更新时间:2024-10-27 00:25:15
本文介绍了如何创建类型的扩展方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我写解析JSON字符串对于任何给定类型的扩展方法。我想使用的类型,而不是像我们已经知道的例子很多实例方法,但我有点觉得它不是由Visual Studio支持。有人可以告诉我吗?以下是方法:

I am writing an extension method for parsing JSON string for any given type. I wanted to use the method on types instead of instances like many examples we already know, but I somewhat feel it is not supported by Visual Studio. Can someone enlighten me here? The following is the method:

public static T ParseJson<T>(this T t, string str) where T: Type { if (string.IsNullOrEmpty(str)) return null; var serializer = new JavaScriptSerializer(); var obj = serializer.Deserialize<T>(str); return obj; }

我要打电话以这种方式方法:

I want to call the method in this fashion:

var instance = MyClass.ParseJson(text);

感谢

Thanks

推荐答案

简短的答案是无法做到的;扩展方法需要在某个实例工作。

The short answer is it cannot be done; extension methods need to work on an instance of something.

更多推荐

如何创建类型的扩展方法

本文发布于:2023-11-04 00:38:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1556481.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类型   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!