原理比较简单,引入System.Reflection命名空间,利用反射查看某种Type下的方法,属性,字段和支持的接口等。
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
while (true)
{
Console.WriteLine("Please input a type:");
string typeStr = Console.ReadLine();
if (typeStr == "exit" || typeStr == "quit")
break;
try
{
Type type = Type.GetType(typeStr);
ListFields(type);
ListMethods(type);
ListInterfaces(type);
}
catch (Exception ex)
{
Console.WriteLine("It is not a valid type!");
}
}
}
#region Methods
public static void ListFields(Type type)
{
Console.WriteLine("******** Fields: ********");
//foreach (FieldInfo item in type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Default))
foreach (FieldInfo item in type.GetFields())
{
Console.WriteLine("->" + item.Name);
}
Console.WriteLine("");
}
public static void ListMethods(Type type)
{
Console.WriteLine("******** Methods: ********");
//foreach (var item in type.GetMethods(BindingFlags.Default | BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic))
var methodInfo = type.GetMethods().Select(m => m.Name).Distinct();
foreach (var item in methodInfo)
{
Console.WriteLine("->" + item);
}
Console.WriteLine("");
}
public static void ListInterfaces(Type type)
{
Console.WriteLine("******** Interfaces: ********");
foreach (var item in type.GetInterfaces())
{
Console.WriteLine("->" + item.Name);
}
Console.WriteLine("");
}
public static void ListProperties(Type type)
{
Console.WriteLine("******** Properties: ********");
foreach (var item in type.GetProperties())
{
Console.WriteLine("->" + item.Name);
}
Console.WriteLine("");
}
#endregion
}
}
******** Methods: ********
->CompareTo
->Equals
->GetHashCode
->ToString
->Parse
->TryParse
->GetTypeCode
->GetType
******** Interfaces: ********
->IComparable
->IFormattable
->IConvertible
->IComparable`1
->IEquatable`1
******** Methods: ********
->Acos
->Asin
->Atan
->Atan2
->Ceiling
->Cos
->Cosh
->Floor
->Sin
->Tan
->Sinh
->Tanh
->Round
->Truncate
->Sqrt
->Log
->Log10
->Exp
->Pow
->IEEERemainder
->Abs
->Max
->Min
->Sign
->BigMul
->DivRem
->ToString
->Equals
->GetHashCode
->GetType
******** Interfaces: ********