IsAssignableFrom、IsInstanceOfType 和 is 关键字,有什么区别? [英] 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
和 is
运算符实际上有什么区别?
As you can see, I have 3 choice, so which one I should to use? Actually what is the difference between IsAssignableFrom
, IsInstanceOfType
, and is
operator?
推荐答案
你可以使用任何你拥有的信息.
You use whatever you have the information for.
如果您有要检查的实例和静态类型,请使用 is
.
If you have an instance and a static type you want to check against, use is
.
如果您没有静态类型,您只有一个 Type
对象,但您有一个要检查的实例,请使用 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
.
如果您没有实例,而只想检查 Type
的理论实例与另一个 Type
的理论实例之间的兼容性,请使用 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
.
但实际上似乎您只是在重新实施 as 运算符(除了你的也适用于不可为空的值类型,这通常不是一个很大的限制).
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 和 is 关键字,有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!