C# 在Guid上转换为泛型类型失败
我试图更改对象属性的类型,当我使用它时,它不会将字符串转换为guid,当我查找时,我发现如果guid是可空的,它将不会通过,所以我跟随了一篇文章,解释了默认方法不适用于可空的,我唯一无法修复的是将x值转换为y实体类型,知道x是字符串,y是guid 自定义更改类型类以跳过可为空的问题C# 在Guid上转换为泛型类型失败,c#,C#,我试图更改对象属性的类型,当我使用它时,它不会将字符串转换为guid,当我查找时,我发现如果guid是可空的,它将不会通过,所以我跟随了一篇文章,解释了默认方法不适用于可空的,我唯一无法修复的是将x值转换为y实体类型,知道x是字符串,y是guid 自定义更改类型类以跳过可为空的问题 public static object ChangeType(object value, Type conversionType) { // Note: This if block was
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)TypeDescriptor.GetConverter(typeof(T)).ConvertFromInvariantString(text);
(instance.GetType())TypeDescriptor.GetConverter(instance.GetType().).ConvertFromInvariantString(text);
如果试图将字符串转换为GUID,为什么不将其传递给GUID构造函数(例如,{GUID temp=new GUID(stringValue)}?如果字符串为空,则创建一个空GUID。那么问题是什么?使用convert.changeType(value,type)如果你真的尝试自己编写代码,那么为什么不将你的尝试包含在问题中。目前,你的问题没有证据表明你已经尝试过,因此将被否决和关闭。你甚至没有提出任何问题。不要只是陈述你的问题和答案暗示问题。直截了当地问问题。好吧,我将发布我所使用的内容。我希望现在这足够证明类型是泛型的,所以它不能是新的Guid(字符串),但是如果知道需要从字符串转到泛型中的Guid,则将遗传转换为字符串并创建Guid。