Use of IsAssignableFrom and “is” keyword in C#

后端 未结 4 2056
谎友^
谎友^ 2020-12-03 02:41

While trying to learn Unity, I keep seeing the following code for overriding GetControllerInstance in MVC:

if(!typeof(IController).IsAssignableF         


        
4条回答
  •  温柔的废话
    2020-12-03 02:54

    A notable difference is also that 'is' makes intuitive sense for testing inheritance or interface implementation, whereas IsAssignableFrom makes anything but sense on the face of it. The name of the Type.IsAssignableFrom method is vague and confusing when applied to testing inheritance or detecting interface implementations. The following wrapper for these purposes would make for much more intuitive, readable application code:

        public static bool CanBeTreatedAsType(this Type CurrentType, Type TypeToCompareWith)
        {
            // Always return false if either Type is null
            if (CurrentType == null || TypeToCompareWith == null)
                return false;
    
            // Return the result of the assignability test
            return TypeToCompareWith.IsAssignableFrom(CurrentType);
        }
    

    Then, one can have more understandable client syntax like:

        bool CanBeTreatedAs = typeof(SimpleChildClass).CanBeTreatedAsType(typeof(SimpleClass));
        CanBeTreatedAs = typeof(SimpleClass).CanBeTreatedAsType(typeof(IDisposable));
    

    The advantage of this method instead of the 'is' keyword is that it can be used at run-time to test unknown, arbitrary Types, whereas the 'is' keyword (and a generic Type parameter) requires compile-time knowledge of specific Types.

提交回复
热议问题