在Guid上,c#强制转换为泛型类型失败

时间:2016-06-13 04:11:40

标签: c#

我正在尝试更改对象属性的类型,当我使用它时,它不会将convert.changetype从字符串转换为guid,当我抬起头时我发现如果guid可以为空它不会传递所以我跟着一篇文章解释说默认方法不适用于nullables我唯一无法修复的是将x值转换为y实体类型,知道x是一个字符串而y是guid。

自定义更改类型类可跳过可以为空的问题

public static object ChangeType(object value, Type conversionType)
    {
        // Note: This if block was taken from Convert.ChangeType as is, and is needed here since we're
        // checking properties on conversionType below.
        if (conversionType == null)
        {
            throw new ArgumentNullException("conversionType");
        } // end if

        // If it's not a nullable type, just pass through the parameters to Convert.ChangeType

        if (conversionType.IsGenericType &&
          conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
        {
            // It's a nullable type, so instead of calling Convert.ChangeType directly which would throw a
            // InvalidCastException (per http://weblogs.asp.net/pjohnson/archive/2006/02/07/437631.aspx),
            // determine what the underlying type is
            // If it's null, it won't convert to the underlying type, but that's fine since nulls don't really
            // have a type--so just return null
            // Note: We only do this check if we're converting to a nullable type, since doing it outside
            // would diverge from Convert.ChangeType's behavior, which throws an InvalidCastException if
            // value is null and conversionType is a value type.
            if (value == null)
            {
                return null;
            } // end if

            // It's a nullable type, and not null, so that means it can be converted to its underlying type,
            // so overwrite the passed-in conversion type with this underlying type
            NullableConverter nullableConverter = new NullableConverter(conversionType);
            conversionType = nullableConverter.UnderlyingType;
        } // end if

        // Now that we've guaranteed conversionType is something Convert.ChangeType can handle (i.e. not a
        // nullable type), pass the call on to Convert.ChangeType

        return Convert.ChangeType(value, conversionType);
    }

试图以这种方式转换它但我无法获得T型

(T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromInvariantString(text);
(instance.GetType())TypeDescriptor.GetConverter(instance.GetType().).ConvertFromInvariantString(text);

1 个答案:

答案 0 :(得分:-2)

如果你试图将字符串转换为GUID,为什么不将它传递给Guid构造函数(例如,{Guid temp = new Guid(stringValue)}?如果字符串为空,则创建一个空的Guid。