簡體   English   中英

C#動態類型轉換

[英]C# dynamic type conversions

我們有2個對象A和B:A是system.string,B是.net原始類型(string,int等)。 我們想編寫通用代碼來將B的轉換(解析)值分配給A.任何建議? 謝謝,阿迪巴爾達

使用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接口出了什么問題?

MSDN有類型轉換概述 ,您可以其中獲得有關該主題的更多信息。 我發現它很有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM