Skip to content

Instantly share code, notes, and snippets.

@Fhernd
Created June 3, 2014 23:57
Show Gist options
  • Save Fhernd/c0ccc6093ce2243f041c to your computer and use it in GitHub Desktop.
Save Fhernd/c0ccc6093ce2243f041c to your computer and use it in GitHub Desktop.
Demostración de los operadores as, is, typeof, y el método GeType en C#.
using System;
using System.IO;
namespace Recetas.Cap03
{
internal class Aplicacion
{
public static void Main()
{
Console.WriteLine();
// Create un nuevo objeto de `StringReader`:
Object objeto = new StringReader("Blog xCSw");
// Comprueba si `objeto` es de tipo StringReader:
if (typeof (StringReader) == objeto.GetType())
{
Console.WriteLine("Uso operador typeof: `objeto` es de tipo `StringReader`.");
}
// Comparación con el operador is:
// ¿`objeto` deriva de `TextReader`?:
if (objeto is TextReader)
{
Console.WriteLine("Uso método GetType: `objecto` es de tipo `TextReader` o clase derivada.");
}
// Usamos GetType para comprobar si `objecto` es de tipo
// System.IO.TextReader:
if (EsTipoDe(objeto, "System.IO.TextReader"))
{
Console.WriteLine("Uso operador is: `objecto` es de tipo `TextReader`");
}
// Uso de operador as:
StringReader lector = objeto as StringReader;
if ( lector != null)
{
Console.WriteLine("Uso operador as: `objecto` es de tipo `StringReader`");
}
Console.WriteLine();
}
///<summary>
/// Comprueba si un objeto ese instancia de un tipo.
///</summary>
///<param value="obj">Instancia de un objeto.</param>
///<param value="tipo">Nombre del tipo</param>
public static bool EsTipoDe(object obj, string tipo)
{
Type t = Type.GetType(tipo, true, true);
return t == obj.GetType() || obj.GetType().IsSubclassOf(t);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment