如何为类型创建扩展方法
我正在编写一个扩展方法,用于解析任何给定类型的 JSON 字符串。我想在类型上使用该方法,而不是像我们已经知道的许多示例那样在实例上使用该方法,但我觉得 Visual Studio 不支持它。有人可以在这里启发我吗?以下是方法:
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;
}
我想以这种方式调用该方法:
var instance = MyClass.ParseJson(text);
谢谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
简短的回答是这是不可能的;扩展方法需要对某个事物的实例起作用。
The short answer is it cannot be done; extension methods need to work on an instance of something.
要使用扩展方法,您必须执行以下操作:
标记“MyClass”不是类型实例 intself,但使用 typeof 将为您提供一个要操作的类型。但这比:
编辑:实际上,扩展方法的代码仍然无法达到您想要的效果。它将始终返回一个“Type”对象,而不是该类型的实例。
To use the extension method, you would have to do:
The token "MyClass" is not a Type instamce intself, but using typeof will get you a Type to operate on. But how is this any better than:
Edit: Actually, the code for the extension method still would not do what you wanted. It will always return a "Type" object, not an instance of that Type.
正如已接受的答案中所述,你不能。但是,假设您有一个可以从 T 实例调用的扩展方法:
您可以编写这样的实用程序方法:
并像这样调用它:
恐怕这是您能做的最好的事情......
As stated in the accepted answer, you can't. However, provided that you have an extension method that can be called from an instance of T:
You could write a utility method like this:
And call it like this:
I am afraid that's the best you can do...
您无法创建适用于类型本身的扩展方法。它们只能在类型的实例上调用。
You can't create extension methods that apply to the type itself. They can only be called on instances of a type.
您可以创建和扩展方法
并像使用它一样
您不必像
instance.Serialize();
使用它,因为大多数时候(如果不是全部时间)它可以是从使用情况推断。You can create and extension method
And use it like
You don't have to use it like
instance.Serialize<Type>();
because most of the time (if not all the time) it can be inferred from the usage.