[英]How toDetermine if an object can be cast to a different type, without IConvertible
我有两个不相关的类:一个不是从另一个派生的。 这些类不实现IConvertible 。 这就是为什么此答案不起作用。
幸运的是,从一个类到另一个类都有一个隐式类运算符。
示例:考虑-System.Data.Entity.DbSet-System.Data.Entity.DbSet。
隐式强制转换运算符:
public static implicit operator DbSet (DbSet<TEntity> entry)
以下作品:
DbSet<MyClass> x = new DbSet<MyClass>();
DbSet y = (DbSet) x; // ok, x properly cast to y
以下内容不起作用:
object x = new DbSet<MyClass>();
object y1 = x as DbSet; // y1 is null, because not derived from DbSet
object y2 = (DbSet) x; // throws InvalidCastException
那么有可能检查一个对象是否可以在不引发异常的情况下转换为另一个对象吗?
您应该能够使用反射来搜索转换方法:
object set = new DbSet<MyClass>();
var conv = set.GetType().GetMethod("op_Implicit", BindingFlags.Static | BindingFlags.Public, null, new[] { set.GetType() }, null);
if (conv != null && conv.ReturnType == typeof(DbSet))
{
var rawSet = (DbSet)conv.Invoke(null, new object[] { set });
}
李给了答案。 我通过创建一个扩展方法来测试它,以尝试将任何对象强制转换为任何类型,只要该对象具有所请求类型的隐式或显式强制转换运算符即可。
public static class ObjectExtensionTryCast
{
public static bool TryCast<T>(this object o, out T castedValue)
{
MethodInfo castMethod = new string[] { "op_Implicit", "op_Explicit" }
.Select(methodName => o.GetType()
.GetMethod(methodName, BindingFlags.Static | BindingFlags.Public, null, new[] { o.GetType() }, null))
.Where(method => method.ReturnType == typeof(T))
.FirstOrDefault();
bool canCast = castMethod != null;
castedValue = canCast ?
(T)castMethod.Invoke(null, new object[] { o }) :
default(T);
return canCast;
}
}
用法:
object o = GetMyObject();
int i;
System.Drawing.Point p;
DBSet dbSet;
bool intCasted = o.TryCast(out i);
bool pointCasted = o.TryCast(out p);
bool dbSetCasted = o.TryCast(out dbSet);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.