System.Type.IsAssignableFrom C# (CSharp) Method

IsAssignableFrom() public method

public IsAssignableFrom ( Type type ) : bool
type Type
return bool
        public bool IsAssignableFrom(Type type)
        {
            // Special hack for handling the merged numeric types
            if (type == typeof (Number))
            {
                if (this == typeof (int) || this == typeof (float) || this == typeof (long) ||
                    this == typeof (byte) || this == typeof (sbyte) || this == typeof (short) ||
                    this == typeof (ushort) || this == typeof (uint) || this == typeof (ulong) ||
                    this == typeof (double))
                {
                    return true;
                }
            }
            // Special hack to allow arbitrary delegates to be force cast into particular delegate
//            if (type == typeof (Delegate) && type.IsAssignableFrom(this))
//            {
//                return true;
//            }


            // Check base type hierarchy
            var current = type;
            while (current != null)
            {
                if (current == this)
                    return true;
                current = current.BaseType;
            }

            // Now check interfaces
            for (var i = 0; i < type.GetInterfaceCount(); i++)
            {
                var item = type.GetInterface(i);
                if (item == this)
                    return true;
            }

            return false;
        }

Usage Example

Ejemplo n.º 1
0
 private object CreateFromString(Type targetType,string name)
 {
     object instance = null;
     if (FrameworkElement != null)
     {
         instance = FrameworkElement.FindResource(name);
         if (instance != null && targetType.IsAssignableFrom(instance.GetType())) return instance;
         instance = null;
     }
     if(Contains(name))
     {
         instance = this[name];
         if (instance != null && targetType.IsAssignableFrom(instance.GetType())) return instance;
         instance = null;
     }
     if (!RequireExactMatch)
     {
         foreach (string key in Keys)
         {
             if (key.Contains(name))
             {
                 instance = this[key];
                 if (instance != null && targetType.IsAssignableFrom(instance.GetType())) return instance;
             }
         }
     }
     return null;
 }
All Usage Examples Of System.Type::IsAssignableFrom