反射 - class 的 GetProperties 接口
Reflection - GetProperties of a class that are Interfaces
我正在使用反射遍历 class 的 Public 属性。
foreach (PropertyInfo prop in instance.GetType().GetProperties())
{
...do work
这让我获得了所有 public 属性。但是我只想获得 Public 作为接口的属性。例如下面我想得到 'session' (这是一个接口)但不是帮助。
public ISession Session { get; set; } //My Interface - i want this
public string Help { get; set; } //I dont want this
使用Type.IsInterface
判断属性的类型是否为接口类型。
Type t = typeof ( YourType );
foreach ( PropertyInfo p in t.GetProperties () )
{
if ( p.PropertyType.IsInterface )
{
// p is an interface property
}
}
我正在使用反射遍历 class 的 Public 属性。
foreach (PropertyInfo prop in instance.GetType().GetProperties())
{
...do work
这让我获得了所有 public 属性。但是我只想获得 Public 作为接口的属性。例如下面我想得到 'session' (这是一个接口)但不是帮助。
public ISession Session { get; set; } //My Interface - i want this
public string Help { get; set; } //I dont want this
使用Type.IsInterface
判断属性的类型是否为接口类型。
Type t = typeof ( YourType );
foreach ( PropertyInfo p in t.GetProperties () )
{
if ( p.PropertyType.IsInterface )
{
// p is an interface property
}
}