IsAssignableFrom, IsInstanceOfType and the is keyword, what is the difference?

前端 未结 4 707
醉梦人生
醉梦人生 2020-12-02 22:41

I have an extension method to safe casting objects, that looks like this:

public static T SafeCastAs(this object obj) {
    if (obj == null)
                


        
4条回答
  •  误落风尘
    2020-12-02 22:57

    I guess you're effectively implementing a version of the as operator that works with value types as well as reference types.

    I'd go for:

    public static T SafeCastAs(this object obj)
    {
        return (obj is T) ? (T) obj : default(T);
    }
    

    IsAssignableFrom works with types, and is works with instances. They will give you the same results in your case, so you should use the simplest version IMHO.

    As for IsInstanceOfType:That is implemented in terms of IsAssignableFrom, so there will be no difference.

    You can prove that by using Reflector to look at the definition of IsInstanceOfType():

    public virtual bool IsInstanceOfType(object o)
    {
        if (o == null)
        {
            return false;
        }
        return this.IsAssignableFrom(o.GetType());
    }
    

提交回复
热议问题