如何获取没有自定义类类型的一个类的属性

时间:2012-08-21 12:16:54

标签: c# c#-4.0 reflection properties getproperties

我有一个Person类:

public class Person 
{
    virtual public long Code { get; set; }
    virtual public string Title { get; set; }       
    virtual public Employee Employee { get; set; }
}

我需要一个通用的解决方案来获取Person类的所有属性,而不使用自定义类类型的属性。表示选择CodeTitle属性。

typeof(Person).GetProperties();           //Title , Code , Employee
typeof(Person).GetProperties().Where(x => !x.PropertyType.IsClass); // Code

如何在没有自定义类类型的情况下选择所有属性? (CodeTitle

2 个答案:

答案 0 :(得分:4)

一种方法是检查ScopeName ModuleType

typeof(Person).GetProperties().Where(x => x.PropertyType.Module.ScopeName == "CommonLanguageRuntimeLibrary")

因为没有直接判断类型是否内置的方法。

要获得其他一些想法,请参阅hereherehere

答案 1 :(得分:0)

我建议使用一个属性:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class SimplePropertyAttribute : Attribute
{
}

public class Employee { }

public class Person
{
    [SimpleProperty]
    virtual public long Code { get; set; }

    [SimpleProperty]
    virtual public string Title { get; set; }

    virtual public Employee Employee { get; set; }
}

internal class Program
{
    private static void Main(string[] args)
    {
        foreach (var prop in typeof(Person)
            .GetProperties()
            .Where(z => z.GetCustomAttributes(typeof(SimplePropertyAttribute), true).Any()))
        {
            Console.WriteLine(prop.Name);
        }

        Console.ReadLine();
    }
}