C# 通用转换功能似乎不适用于 Guids

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/393731/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 01:46:44  来源:igfitidea点击:

Generic conversion function doesn't seem to work with Guids

c#.netgenericstypeconverter

提问by mattruma

I have the following code:

我有以下代码:

public static T ParameterFetchValue<T>(string parameterKey)
{
    Parameter result = null;

    result = ParameterRepository.FetchParameter(parameterKey);

    return (T)Convert.ChangeType(result.CurrentValue, typeof(T), CultureInfo.InvariantCulture);  
}

The type of result.CurrentValueis string. I would like to be able to convert it to Guid but I keep getting the error:

的类型result.CurrentValue是 string。我希望能够将其转换为 Guid,但我不断收到错误消息:

Invalid cast from System.String to System.Guid

从 System.String 到 System.Guid 的无效转换

This works perfectly with primitive data types.
Is there any way to make this work for non-primitive data types?

这适用于原始数据类型。
有什么方法可以使这项工作适用于非原始数据类型

采纳答案by Marc Gravell

How about:

怎么样:

T t = (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromInvariantString(text);

Works fine for Guidand most other types.

适用于Guid和大多数其他类型。

回答by nazim hatipoglu

Try This:

尝试这个:

public object ChangeType(object value, Type type)
    {
        if (value == null && type.IsGenericType) return Activator.CreateInstance(type);
        if (value == null) return null;
        if (type == value.GetType()) return value;
        if (type.IsEnum)
        {
            if (value is string)
                return Enum.Parse(type, value as string);
            else
                return Enum.ToObject(type, value);
        }
        if (!type.IsInterface && type.IsGenericType)
        {
            Type innerType = type.GetGenericArguments()[0];
            object innerValue = ChangeType(value, innerType);
            return Activator.CreateInstance(type, new object[] { innerValue });
        }
        if (value is string && type == typeof(Guid)) return new Guid(value as string);
        if (value is string && type == typeof(Version)) return new Version(value as string);
        if (!(value is IConvertible)) return value;
        return Convert.ChangeType(value, type);
    }