OhSnap
OhSnap

Reputation: 376

Get Properties of baseclass and specific inherited class

I have a base class CrmObject and a few classes that inherit it (Aufgabe, Kontakt, ...). I only have a string-value for the child-class and I want to get both the Properties of CrmObject and the specific child-class in one Statement.

I'd get the properties of the child-class like this:

var propertyInfos = typeof(CrmObject).Assembly.GetType("Aufgabe").GetProperties().Where(p => Attribute.IsDefined(p, typeof(ImportParameter)));

But I'd like to get the Properties of CrmObject, too. Possibly within the same statement.

[UPDATE] This should be it. I'll test it later. Thank you, guys. :)

var propertyInfos = typeof(CrmObject).Assembly.GetType("DAKCrmImport.Core." +crmType).G‌​etProperties().Where(p => Attribute.IsDefined(p, typeof(ImportParameter)));

Weirdly enough you don't need the bindingflag parameter to flatten the hierarchy. Apparently it's the default value? Well .. whatever. It works :)

Upvotes: 1

Views: 819

Answers (2)

Domysee
Domysee

Reputation: 12854

As Mark said, you need to specify BindingFlags.FlattenHierarchy.
But when you specify the BindingFlags, you need to specify exactly what you want. That means that you also have to specify BindingFlags.Instance to get the instance members and BindingFlags.Public to include public members.

So the command would look like this:

var propertyInfos = typeof(CrmObject).Assembly.GetType(crmType).G‌​etProperties(BindingFlags.FlattenHierarchy | BindingFlags.Instance | BindingFlags.Public).Where(p => Attribute.IsDefined(p, typeof(ImportParameter)));

You can read more about it in this great SO answer and in the documentation of Type.GetProperties.

Upvotes: 1

Greg
Greg

Reputation: 1116

Works fine for me.

public class CrmObject
{
    [ImportParameter]
    public string Name { get; set; }
}

public class Aufgabe : CrmObject
{
    [ImportParameter]
    public int Id { get; set; }
}

public class ImportParameterAttribute : Attribute
{

}

public class InheritenceProgram
{
    public static void Main()
    {
        var propertyInfos = typeof(CrmObject).Assembly.GetType("Aufgabe").GetProperties().Where(p => Attribute.IsDefined(p, typeof(ImportParameterAttribute)));
        var list = propertyInfos.ToList();
    }
}

Upvotes: 1

Related Questions