如何在 C# 中制作通用数字解析器?

How to make a generic number parser in C#?(如何在 C# 中制作通用数字解析器?)
本文介绍了如何在 C# 中制作通用数字解析器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要将字符串解析为 int,调用 Int32.Parse(string),对于 double,Double.Parse(string),对于 long,Int64.Parse(string) 等等..

To parse a string to an int, one calls Int32.Parse(string), for double, Double.Parse(string), for long, Int64.Parse(string), and so on..

是否可以创建一个使其通用的方法,例如 ParseString<T>(string)?其中 T 可以是 Int32Double 等.我注意到类型的数量没有实现任何通用接口,而 Parse 方法没有任何共同的父级.

Is it possible to create a method that makes it generic, for example, ParseString<T>(string)? where T can be Int32, Double, etc. I notice the number of types don't implement any common interface, and the Parse methods don't have any common parent.

有什么方法可以实现这个或类似的东西吗?

Is there any way to achieve this or something similar to this?

推荐答案

你基本上必须使用反射来找到相关的静态 Parse 方法,调用它,并将返回值转换回<代码>T.或者,您可以使用 Convert.ChangeType 或获取相关的TypeDescriptor 和相关的 TypeConverter.

You'd basically have to use reflection to find the relevant static Parse method, invoke it, and cast the return value back to T. Alternatively, you could use Convert.ChangeType or get the relevant TypeDescriptor and associated TypeConverter.

一种更有限但更有效(在某些方面也很简单)的方法是保留从类型到解析委托的字典 - 将委托转换为 Func<string, T> 并调用它.这将允许您对不同的类型使用不同的方法,但您需要知道需要预先转换为的类型.

A more limited but efficient (and simple, in some ways) approach would be to keep a dictionary from type to parsing delegate - cast the delegate to a Func<string, T> and invoke it. That would allow you to use different methods for different types, but you'd need to know the types you needed to convert to up-front.

无论你做什么,你都不能指定一个通用的约束来保证它在编译时是安全的.真的你需要像我的想法 静态接口 用于那种事情.如前所述,有 IConvertible 接口,但这并不一定意味着您将能够从 string 进行转换.另一种类型可以实现IConvertible,而无需通过任何方式从字符串转换为该类型.

Whatever you do, you won't be able to specify a generic constraint which would make it safe at compile-time though. Really you need something like my idea of static interfaces for that kind of thing. As mentioned, there's the IConvertible interface, but that doesn't necessarily mean that you'll be able to convert from string. Another type could implement IConvertible without having any way of converting to that type from a string.

这篇关于如何在 C# 中制作通用数字解析器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)