using System;
interface IAnimal
{
}
class Cat: IAnimal
{
}
class Program
{
public static void Main(string[] args)
{
IAnimal cat = new Cat();
// Console.WriteLine(cat.GetType());
// This would only give me the type of
// the backing store, i.e. Cat. Is there a
// way I can get to know that the identifier
// cat was declared as IAnimal?
Console.ReadKey();
}
}
Aggiornamento: Grazie a Dan Bryant per il promemoria.differenziare la natura utilizzato per fare riferimento a un oggetto e il suo tipo di memoria di supporto
using System;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;
namespace TypeInfo
{
class Program
{
public static void Main(string[] args)
{
IAnimal myCat = new Cat();
ReflectOnType();
Console.ReadKey();
}
public static void ReflectOnType()
{
Assembly.GetExecutingAssembly().
GetType("TypeInfo.Program").
GetMethod("Main",
BindingFlags.Static| BindingFlags.Public).
GetMethodBody().LocalVariables.
ToList().
ForEach(l => Console.WriteLine(l.LocalType));
}
}
interface IAnimal { }
class Cat : IAnimal { }
}
E 'possibile, ma è necessario riflettere sul metodo stesso; LocalVariableInfo ha un LocalType che puoi utilizzare. Vedi qui: http://stackoverflow.com/questions/2696691/can-i-get-the-method-local-variables-through-a-stack-trace-in-c –
Perché dovresti farlo quando il il tipo è già disponibile staticamente? –
@Dan Bryant: Accidenti! Dannazione! Dannazione! Io uso LocalVariableInfo e LocalType tutto il tempo. Cosa c'è di sbagliato in me? E l'ho usato in uno scenario simile prima. Dannazione! Perché ho fatto questa domanda? Grazie mille per il promemoria. –