Advertisement
Fhernd

ComprobacionTipoObjeto.cs

Jul 28th, 2014
402
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.92 KB | None | 0 0
  1. using System;
  2. using System.IO;
  3.  
  4. namespace Recetas.Cap03
  5. {
  6.     internal class Aplicacion
  7.     {
  8.         public static void Main()
  9.         {
  10.             Console.WriteLine();
  11.            
  12.             // Create un nuevo objeto de `StringReader`:
  13.             Object objeto = new StringReader("Blog xCSw");
  14.            
  15.             // Comprueba si `objeto` es de tipo StringReader:
  16.             if (typeof (StringReader) == objeto.GetType())
  17.             {
  18.                 Console.WriteLine("Uso operador typeof: `objeto` es de tipo `StringReader`.");
  19.             }
  20.            
  21.             // Comparación con el operador is:
  22.             // ¿`objeto` deriva de `TextReader`?:
  23.             if (objeto is TextReader)
  24.             {
  25.                 Console.WriteLine("Uso método GetType: `objecto` es de tipo `TextReader` o clase derivada.");
  26.             }
  27.            
  28.             // Usamos GetType para comprobar si `objecto` es de tipo
  29.             // System.IO.TextReader:
  30.             if (EsTipoDe(objeto, "System.IO.TextReader"))
  31.             {
  32.                 Console.WriteLine("Uso operador is: `objecto` es de tipo `TextReader`");
  33.             }
  34.            
  35.             // Uso de operador as:
  36.             StringReader lector = objeto as StringReader;
  37.             if ( lector != null)
  38.             {
  39.                 Console.WriteLine("Uso operador as: `objecto` es de tipo `StringReader`");
  40.             }
  41.            
  42.             Console.WriteLine();
  43.         }
  44.    
  45.         ///<summary>
  46.         /// Comprueba si un objeto ese instancia de un tipo.
  47.         ///</summary>
  48.         ///<param value="obj">Instancia de un objeto.</param>
  49.         ///<param value="tipo">Nombre del tipo</param>
  50.         public static bool EsTipoDe(object obj, string tipo)
  51.         {
  52.             Type t = Type.GetType(tipo, true, true);
  53.            
  54.             return t == obj.GetType() || obj.GetType().IsSubclassOf(t);
  55.         }
  56.     }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement