【发布时间】:2011-05-29 03:51:31
【问题描述】:
我正在做一个项目,我需要在其中注册所有属性,因为系统非常庞大,需要大量工作来注册我想要依赖于 Xaml 的所有属性。
目标是找到位于树顶部的所有属性。
基本上是这样
public class A{
public int Property1 { get; set; }
}
public class B : A{
public int Property2 { get; set; }
public virtual int Property3 { get; set; }
}
public class C : B{
public override int Property3 { get; set; }
public int Property4 { get; set; }
public int Property5 { get; set; }
}
最终结果会是这样的
A.Property1
B.Property2
B.Property3
C.Property4
C.Property5
如果您注意到我不想接受被覆盖的属性,因为我在执行类似操作时搜索属性的方式
以 C.Property3 为例,它找不到它,它将检查 C 的基本类型并在那里找到它。
这是我目前所拥有的。
public static void RegisterType( Type type )
{
PropertyInfo[] properties = type.GetProperties( BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.GetProperty | BindingFlags.SetProperty );
if ( properties != null && properties.Length > 0 )
{
foreach ( PropertyInfo property in properties )
{
// if the property is an indexers then we ignore them
if ( property.Name == "Item" && property.GetIndexParameters().Length > 0 )
continue;
// We don't want Arrays or Generic Property Types
if ( (property.PropertyType.IsArray || property.PropertyType.IsGenericType) )
continue;
// Register Property
}
}
}
我想要的是:
- 非被覆盖、非静态、非私有 的公共属性
- 允许获取和设置属性
- 它们不是数组或泛型类型
- 它们是树的顶部,即示例中的 C 类是最高的(属性列表示例正是我要寻找的)
- 它们不是索引器属性 (this[index])
【问题讨论】:
标签: c# .net reflection types propertyinfo