如果属性是用户定义的,我现在如何在通过Type.GetProperties()获得的列表中?
例如
class test
{
public string propertyOne{get;set;}
public string propertyTwo{get;set;}
}用typeof(test).GetProperties()我得到了两个PropertyInfo,我现在怎么能让它们是用户定义的呢?
有关上下文的信息,下面是应该通过的测试
[Test]
public void GetFullNameScalarPropertiesTest()
{
// Act
var properties = ReflectionHelper.GetFullNameScalarProperties(typeof(Parent));
// Assert
Assert.True(properties.Contains("PropertyOne"));
Assert.True(properties.Contains("Child.PropertyTwo"));
Assert.True(properties.Contains("Child.GrandChild.PropertyThree"));
Assert.That(properties.Count, Is.EqualTo(3));
}
class Parent
{
public Parent()
{
Child = new Child();
}
public string PropertyOne { get; set; }
public Child Child { get; set; }
}
class Child
{
public Child()
{
GrandChild = new GrandChild();
}
public string PropertyTwo { get; set; }
public GrandChild GrandChild { get; set; }
}
class GrandChild
{
public string PropertyThree { get; set; }
}因此,在递归方法中,我将获取属性并使用名称创建一个列表
通过此测试的代码为
public static IList<string> GetFullNameScalarProperties(Type type)
{
var lista = new List<string>();
var path = string.Empty;
var properties = type.GetProperties();
foreach (var propertyInfo in properties)
GetFullNameScalarProperties(propertyInfo, path, lista);
return lista;
}
private static void GetFullNameScalarProperties(PropertyInfo propertyInfo, string path, ICollection<string> lista)
{
if (!string.IsNullOrEmpty(path))
path += ".";
path += propertyInfo.Name;
if (propertyInfo.PropertyType.FullName != null)
if (propertyInfo.PropertyType.FullName.StartsWith("System"))
{
lista.Add(path);
return;
}
var properties = propertyInfo.PropertyType.GetProperties();
foreach (var pi in properties)
GetFullNameScalarProperties(pi, path, lista);
}发布于 2011-01-27 15:32:17
不清楚你所说的“用户定义”是什么意思--你是想找出一个自动实现的属性和一个手工编写的属性之间的区别吗?如果是这样,则自动实现的属性将在getter和setter上具有[CompilerGenerated]属性。
using System;
using System.Runtime.CompilerServices;
class Program
{
public int AutomaticallyImplemented { get; set; }
public int HandWritten {
get { return 0; }
set {}
}
static void Main()
{
foreach (var property in typeof(Program).GetProperties())
{
bool auto = property.GetGetMethod().IsDefined
(typeof(CompilerGeneratedAttribute), false);
Console.WriteLine("{0}: {1}", property.Name, auto);
}
}
}显然,您通常会首先检查是否有getter :)
发布于 2011-01-27 15:30:54
没有什么比“用户定义”属性更好的了。要了解在继承层次结构中以哪种类型声明属性,请查看PropertyInfo.DeclaringType。
发布于 2011-01-27 15:32:27
如果要确定属性是否继承,请将PropertyInfo.DeclaringType与正在测试的类型进行比较
https://stackoverflow.com/questions/4813732
复制相似问题