如何创建类型的扩展方法 [英] How to create extension methods for Types
本文介绍了如何创建类型的扩展方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我写解析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.
这篇关于如何创建类型的扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文