如何在C#中创建通用数字解析器? [英] How to make a generic number parser in C#?

查看:107
本文介绍了如何在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 和关联的

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#中创建通用数字解析器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆