IsAssignableFrom,IsInstanceOfType和是关键字,有什么区别? [英] IsAssignableFrom, IsInstanceOfType and the is keyword, what is the difference?

查看:205
本文介绍了IsAssignableFrom,IsInstanceOfType和是关键字,有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个安全的投放对象的扩展方法,如下所示:

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.

如果您没有实例,而只想检查类型和另一个类型,请使用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆