我正在使用此扩展方法来转换项目中的对象.但它无法转换GUID,因为它不实现IConvertible接口但转换我总是必须使用新的Guid(fooobject),但我想我可以使用此方法将对象转换为GUID.任何想法我们如何才能灵活地使用GUID.
扩展方法是
public static T ToType<T>(this object val, T alt) where T : struct, IConvertible
{
try
{
return (T)Convert.ChangeType(val, typeof(T));
}
catch
{
return alt;
}
}
最佳答案 因为您具有要转换为的类型实现
IConvertible
interface(而
Guid
structure)的约束,所以您无法创建重载,如下所示:
public static Guid ToType(this object val, Guid alt)
{
try
{
// Convert here.
}
catch
{
return alt;
}
}
当你通过一个Guid时,它会因为section 7.4.2 of the C# specification(强调我的)而解决:
Once the candidate function members and the argument list have been
identified, the selection of the best function member is the same in
all cases:
- Given the set of applicable candidate function members, the best function member in that set is located.
鉴于Guid是比类型参数T更具体的匹配,将调用您的第二个方法.
请注意,如果删除了IConvertible接口约束,则可以在单个方法中处理此问题,但是您必须能够使用逻辑来处理为T传递的任何结构(此处的TypeConverter
实例将非常方便).