How get properties of one class without custom class types
-
27-06-2021 - |
Question
I have a Person class :
public class Person
{
virtual public long Code { get; set; }
virtual public string Title { get; set; }
virtual public Employee Employee { get; set; }
}
I need to a generic solution for get all properties of Person class without properties by custom class types. Means select Code
, Title
properties.
typeof(Person).GetProperties(); //Title , Code , Employee
typeof(Person).GetProperties().Where(x => !x.PropertyType.IsClass); // Code
How can I select all properties without custom class types? (Code
, Title
)
Solution
OTHER TIPS
I would suggest using an attribute:
[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();
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow