【发布时间】:2014-04-24 20:20:56
【问题描述】:
我们有 2 个对象 A 和 B:A 是 system.string,B 是一些 .net 原始类型(string、int 等)。我们想编写通用代码将 B 的转换(解析)值分配给 A。有什么建议吗?谢谢,阿迪巴尔达
【问题讨论】:
标签: c#
我们有 2 个对象 A 和 B:A 是 system.string,B 是一些 .net 原始类型(string、int 等)。我们想编写通用代码将 B 的转换(解析)值分配给 A。有什么建议吗?谢谢,阿迪巴尔达
【问题讨论】:
标签: c#
最实用、最通用的字符串转换方法是使用TypeConverter:
public static T Parse<T>(string value)
{
// or ConvertFromInvariantString if you are doing serialization
return (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromString(value);
}
比实现IConvertible 等更多的类型具有类型转换器,您还可以在编译时将转换器添加到新类型;
[TypeConverter(typeof(MyCustomConverter))]
class Foo {...}
class MyCustomConverter : TypeConverter {
// override ConvertFrom/ConvertTo
}
如果您需要,也可以在运行时(对于您不拥有的类型):
TypeDescriptor.AddAttributes(typeof(Bar),
new TypeConverterAttribute(typeof(MyCustomConverter)));
【讨论】:
如前所述,System.Convert 和 IConvertible 将是第一个赌注。如果由于某种原因您不能使用这些(例如,如果内置类型的默认系统转换不适合您),一种方法是创建一个字典来保存每个转换的委托,并在其中进行查找以在需要时找到正确的转换。
例如;当您想从 String 转换为 X 类型时,您可以使用以下内容:
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
Console.WriteLine(SimpleConvert.To<double>("5.6"));
Console.WriteLine(SimpleConvert.To<decimal>("42"));
}
}
public static class SimpleConvert
{
public static T To<T>(string value)
{
Type target = typeof (T);
if (dicConversions.ContainsKey(target))
return (T) dicConversions[target](value);
throw new NotSupportedException("The specified type is not supported");
}
private static readonly Dictionary<Type, Func<string, object>> dicConversions = new Dictionary <Type, Func<string, object>> {
{ typeof (Decimal), v => Convert.ToDecimal(v) },
{ typeof (double), v => Convert.ToDouble( v) } };
}
显然,您可能希望在自定义转换例程中做一些更有趣的事情,但这说明了这一点。
【讨论】:
已经存在的 System.Convert 类和 IConvertible 接口有什么问题?
【讨论】:
有一个overview of type conversions at MSDN,您可以在其中获取有关该主题的更多信息。我发现它很有用。
【讨论】: