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

mat*_*uma 39 .net c# generics typeconverter

我有以下代码:

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

    result = ParameterRepository.FetchParameter(parameterKey);

    return (T)Convert.ChangeType(result.CurrentValue, typeof(T), CultureInfo.InvariantCulture);  
}
Run Code Online (Sandbox Code Playgroud)

result.CurrentValue字符串的类型.我希望能够将其转换为Guid,但我一直收到错误:

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

这与原始数据类型完美配合.
有没有办法让这个工作非原始数据类型

Mar*_*ell 100

怎么样:

T t = (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromInvariantString(text);
Run Code Online (Sandbox Code Playgroud)

适用于Guid大多数其他类型.

  • 使用ConvertFromInvariantString时要小心.如果您的类型是DateTime并且您有国际日期格式,这将会爆炸.我根据这个答案找到了一个非常难以找到的bug. (4认同)
  • 是的,同意了。我仍然赞成您的答案,因为它非常有用。只是向其他人指出这个潜在的问题,因为它让我很痛苦。 (2认同)