IsAssignableFrom,IsInstanceOfType和是关键字,有什么区别? [英] IsAssignableFrom, IsInstanceOfType and the is keyword, what is the difference?
问题描述
我有一个安全的投放对象的扩展方法,如下所示:
I have an extension method to safe casting objects, that looks like this:
public static T SafeCastAs<T>(this object obj) {
if (obj == null)
return default(T);
// which one I should use?
// 1. IsAssignableFrom
if (typeof(T).IsAssignableFrom(obj.GetType()))
return (T)obj;
// 2. IsInstanceOfType
if (typeof(T).IsInstanceOfType(obj))
return (T) obj;
// 3. is operator
if (obj is T)
return (T) obj;
return default(T);
}
如你所见,我有3个选择,使用?实际上 IsAssignableFrom
, IsInstanceOfType
和之间的区别是
运算符?
推荐答案
您可以使用任何您拥有的信息。
You use whatever you have the information for.
您有一个要检查的实例和静态类型,请使用是
If you have an instance and a static type you want to check against, use is
.
具有静态类型,你只有一个类型
对象,但你有一个要检查的实例,使用 IsInstanceOfType
。
If you don't have the static type, you just have a Type
object, but you have an instance you want to check, use IsInstanceOfType
.
如果您没有实例,而只想检查类型$ c $的理论实例之间的兼容性c>和另一个
类型
,请使用 IsAssignableFrom
。
If you don't have an instance and you just want to check the compatibility between a theoretical instance of a Type
and another Type
, use IsAssignableFrom
.
但实际上似乎你只是重新实现作为operator < a>(除了你的也可以用于不可为null的值类型,这通常不是一个大的限制)。
But really is seems like you are just re-implementing the as operator (except that yours would also work for non-nullable value types, which is usually not a big limitation).
这篇关于IsAssignableFrom,IsInstanceOfType和是关键字,有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!