1. 程式人生 > >通過泛型,將string轉換為指定類型

通過泛型,將string轉換為指定類型

quest model urn grid hyperlink ror return exceptio ngs

Generic TryParse

You should use the TypeDescriptor class:

public static T Convert<T>(this string input)
{
    try
    {
        var converter = TypeDescriptor.GetConverter(typeof(T));
        if(converter != null)
        {
            // Cast ConvertFromString(string text) : object to (T)
            return (T)converter.ConvertFromString(input);
        }
        return default(T);
    }
    catch (NotSupportedException)
    {
        return default(T);
    }
}

自己的版本

public static T GetAppSetting<T>(string key)
        {
            T result;
            var value = ConfigurationManager.AppSettings[key];
            if (string.IsNullOrEmpty(value))
            {
                throw new ConfigurationErrorsException($"Can not find app setting by key: {key}
"); } Type type = typeof(T); var converter = TypeDescriptor.GetConverter(type); if (converter == null) { throw new ObjectNotFoundException($"Can not get the converter for Type: {type.FullName}"); }
try { var obj = converter.ConvertFromString(value); result = (T) obj; } catch (Exception ex) { throw new ConfigurationErrorsException( $"Can not read the app setting by key: {key} with Type {type.FullName}", ex); } return result; }

通過泛型,將string轉換為指定類型