我有一个Person类:
public class Person
{
virtual public long Code { get; set; }
virtual public string Title { get; set; }
virtual public Employee Employee { get; set; }
}
我需要一个通用的解决方案来获取Person类的所有属性,而不使用自定义类类型的属性。表示选择Code
,Title
属性。
typeof(Person).GetProperties(); //Title , Code , Employee
typeof(Person).GetProperties().Where(x => !x.PropertyType.IsClass); // Code
如何在没有自定义类类型的情况下选择所有属性? (Code
,Title
)
答案 0 :(得分:4)
typeof(Person).GetProperties().Where(x => x.PropertyType.Module.ScopeName == "CommonLanguageRuntimeLibrary")
因为没有直接判断类型是否内置的方法。
答案 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();
}
}