How to Get the List of Properties of a Class

How to get a list of property names in a class in certain a order

Let's implement a simple method to get how deep is the class in the class hierarchy

null <- object <- ... <- MyBaseClass <- MyClass <- ...

Implementation

// 0     - null
// 1 - object
// ...
// n - MyBaseClass
// n + 1 - MyClass
// ...
private static int TypeLevel(Type type) {
if (null == type)
return 0;

return TypeLevel(type.BaseType) + 1;
}

And then with a help of Linq sort by this criterium, the only little trick is to use DeclaringType - where (in which class) the property has been declared:

// fieldNames are actually properties' names
string[] fieldNames = typeof(MyClass)
.GetProperties()
.OrderBy(p => TypeLevel(p.DeclaringType)) // <- base first, derived last
.ThenBy(p => p.Name) // <- let's organize properties within each class
.Select(p => p.Name)
.ToArray();

Console.Write(string.Join(Environment.NewLine, fieldNames));

Outcome:

BaseField1
BaseField2
BaseField3
BaseField4
Field1
Field2
Field3
Field4

Finally, your method can be something like this:

// we don't want any restictions like "where T : class"
private void MyMethod<T>(List<T> listData) {
...
string[] fieldNames = typeof(T)
.GetProperties()
.OrderBy(p => TypeLevel(p.DeclaringType)) // <- base first, derived last
.ThenBy(p => p.Name) // <- let's organize properties within each class
.Select(p => p.Name)
.ToArray();

...
}

Get the list of 'property' class attributes of a class in python

propertys are defined on the class, if you try to access them via an instance, their __get__ is called. So make it a class method instead:

    @classmethod
def get_props(cls):
return [x for x in dir(cls)
if isinstance( getattr(cls, x), property) ]

Get List of Properties from a Class T using C# Reflection

Your binding flags are incorrect.

Since your properties are not static properties but rather instance properties, you need to replace BindingFlags.Static with BindingFlags.Instance.

propertyInfos = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

This will appropriately look for public, instance, non-static properties on your type. You can also omit the binding flags entirely and get the same results in this case.

C# get all properties of a certain type of an object in C#

The code below demonstrates how to get all the properties of type IFormFile from the object car.

As it was mentioned in the comments, Reflection API is quite slow - consider caching PropertyInfo objects, or what is better - using Expressions to compile a delegate, that would iterate over the object properties and put their values into a target collection.

void Main()
{
var car = new Car();

var imagens = typeof(Car).GetProperties()
.Where(x => x.PropertyType == typeof(IFormFile))
.Select(x => (IFormFile)x.GetValue(car))
.Where(x => x != null)
.ToList();
}
PropertyInfo caching

Below is a sample of how the code above can be transformed to use cached PropertyInfo objects:

void Main()
{
var car = new Car();
var imagens = PropertyGetter<Car, IFormFile>.GetValues(car);
}

public static class PropertyGetter<TObject, TPropertyType>
{
private static readonly PropertyInfo[] _properties;

static PropertyGetter()
{
_properties = typeof(TObject).GetProperties()
// "IsAssignableFrom" is used to support derived types too
.Where(x => typeof(TPropertyType).IsAssignableFrom(x.PropertyType))
// Check that the property is accessible
.Where(x => x.GetMethod != null && x.GetMethod.IsPublic && !x.GetMethod.IsStatic)
.ToArray();
}

public static TPropertyType[] GetValues(TObject obj)
{
var values = _properties
.Select(x => (TPropertyType) x.GetValue(obj))
.ToArray();

return values;
}
}
Expression-based

Another sample showing how it's possible to implement the logic of selecting property values of specific type based on Expressions.

public static class PropertyGetterEx<TObject, TPropertyType>
{
private static readonly Func<TObject, TPropertyType[]> _getterFunc;

static PropertyGetterEx()
{
// The code below constructs the following delegate:
//
// o => object.ReferenceEquals(o, null)
// ? null
// : new TPropertyType[] { o.Prop1, o.Prop2, ... };
//

// An expression for the parameter `o`
var objParam = Expression.Parameter(typeof(TObject), "o");

// Create expressions for `o.Prop1` ... `o.PropN`
var propertyAccessExprs = GetPropertyInfos()
.Select(x => Expression.MakeMemberAccess(objParam, x));

// Create an expression for `new TPropertyType[] { o.Prop1, o.Prop2, ... }`
var arrayInitExpr = Expression.NewArrayInit(
typeof(TPropertyType),
propertyAccessExprs);

// Create an expression for `object.ReferenceEquals(o, null)`
var refEqualsInfo = typeof(object).GetMethod(nameof(object.ReferenceEquals));
var refEqualsExpr = Expression.Call(
refEqualsInfo,
objParam,
Expression.Constant(null, typeof(TPropertyType)));

// The condition expression
var conditionExpr = Expression.Condition(
refEqualsExpr,
Expression.Constant(null, typeof(TPropertyType[])),
arrayInitExpr);

_getterFunc = Expression
.Lambda<Func<TObject, TPropertyType[]>>(
conditionExpr,
objParam)
.Compile();
}

private static PropertyInfo[] GetPropertyInfos()
{
var properties = typeof(TObject).GetProperties()
// "IsAssignableFrom" is used to support derived types too
.Where(x => typeof(TPropertyType).IsAssignableFrom(x.PropertyType))
// Check that the property is accessible
.Where(x => x.GetMethod != null && x.GetMethod.IsPublic && !x.GetMethod.IsStatic)
.ToArray();

return properties;
}

public static TPropertyType[] GetValues(TObject obj)
{
return _getterFunc(obj);
}
}
Benchmark results

Below are benchmark results for the 3 approaches provided above (no cache, with PropertyInfo cache, Expression-based). As expected, the Expression-based solution performs much better than the others:

|               Method |      Mean |    Error |   StdDev | Rank |
|--------------------- |----------:|---------:|---------:|-----:|
| NoCache | 789.99 ns | 4.669 ns | 4.139 ns | 3 |
| PropertyInfoCache | 417.32 ns | 3.271 ns | 3.059 ns | 2 |
| ExpressionBasedCache | 27.55 ns | 0.091 ns | 0.085 ns | 1 |

PHP: Get list of all Class Properties (public and private) without instantiating class

You can still use ReflectionClass, php.net tells us the following about the constructor argument:

Either a string containing the name of the class to reflect, or an object.

so

<?php

class SomeClass
{
private $member;

private $othermember;
}

$cls = new ReflectionClass( SomeClass::class );
print_r( $cls->getProperties() );

will print:

Array
(
[0] => ReflectionProperty Object
(
[name] => member
[class] => SomeClass
)
[1] => ReflectionProperty Object
(
[name] => othermember
[class] => SomeClass
)
)

how to get javascript class properties list

The issue is that you're using Object.getOwnPropertyNames wrong. You don't need to use call on it, you just call it.* And you need to pass an instance of Student; the class object itself doesn't have any properties. The properties are created in the constructor, and nothing can tell you what properties the instance will have from looking at the class object.

class Student {    constructor(name, birthDate) {        this.name = name;        this.birthDate = birthDate;    }
get age() { return 2018 - this.birthDate; }
display() { console.log(`name ${this.name}, birth date: ${this.birthDate}`); }}
console.log(Object.getOwnPropertyNames(new Student));

vb.net list class properties with values

Type.GetMembers returns a list of MemberInfo objects, one per member of the type. However, not all members have values. Fields and properties have values, so if you get the list of just the fields or just the properties, you can ask them for their values. But things like methods don't have a value. You may be able to invoke them and read their return values, but that's different from reading the value of a property or a field.

In other words, you have to work differently with each member, depending on what kind of member it is. Since MemberInfo is the lowest common-denominator, it doesn't have any of the functionality which only works on some of the members. If you want the additional functionality available to you, you'll need to use one of the more specific methods like GetProperties or GetFields.

Since your class contains properties, you probably want to get the list of properties:

Public Class Person
Public Property Name As String
Public Property Age As Integer

Public Overrides Function ToString() As String
Dim bigStr As String = ""
For Each p As PropertyInfo In Me.GetType().GetProperties()
bigStr &= p.Name & " " & p.GetValue(Me)?.ToString()
Next
Return bigStr
End Function
End Class

How can I get list of class properties in Swift 4?

You can get `properties like below :

class ClassTest {
var prop1: String?
var prop2: Bool?
var prop3: Int?
}

let mirror = Mirror(reflecting: ClassTest())
print(mirror.children.flatMap { $0.label }) // ["prop1", "prop2", "prop3"]


Related Topics



Leave a reply



Submit