Wat*_* v2 6 .net c# reflection
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();
}
}
Run Code Online (Sandbox Code Playgroud)
更新: 感谢Dan Bryant的提醒.
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 { }
}
Run Code Online (Sandbox Code Playgroud)
根据上面的建议,我将其发布为答案。有关更多背景信息,请参阅上面的评论。
您表示您仍然看到 LocalVariableInfo 的“后备存储”。这对我来说意味着声明纯粹在源代码中,而实际上根本没有编码在方法中。您选择使用接口作为“声明”类型的事实是无关紧要的,因为编译器选择对局部变量槽使用更具体的类型。尝试在 DLL 输出上运行 ILdasm,您可以看到这是否属实。如果是,您唯一的选择就是实际查看源代码,因为编译版本中实际上不存在该信息。
| 归档时间: |
|
| 查看次数: |
178 次 |
| 最近记录: |