是否有可能使在C#泛型号码分析器?分析器、能使、型号

2023-09-04 00:30:32 作者:我笑了你却哭了

要分析字符串为int,一是调用 Int32.Parse(字符串),双, Double.Parse(字符串),长期, Int64.Parse(字符串),等等..

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>(字符串)?其中T可以是的Int32,双人等我注意到数类型不实现任何通用的接口,和解析方法不具有任何公共的父。

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 types don't implement any common interface, and the Parse methods don't have any common parent.

有没有办法实现这个或者类似的东西?

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

推荐答案

您会基本上都要使用反射来找到相关的静态解析方法,调用它,将返回值回 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键&LT;字符串,T&GT; 并调用它。这将允许您使用不同的方法针对不同类型,但你需要知道你需要转换到前期的类型。

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 接口,但是,这并不一定意味着你就可以从字符串转换。另一种类型的可以的实施 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.

 
精彩推荐
图片推荐