Get Property from a generic Object in C#

Eli*_*eth 3 c# generics get properties object

have a look at this code please:

public void BindElements<T>(IEnumerable<T> dataObjects)
{
    Paragraph para = new Paragraph();

    foreach (T item in dataObjects)
    {
        InlineUIContainer uiContainer =
            this.CreateElementContainer(item.FirstName ????? )              
        para.Inlines.Add(uiContainer);
    }                         

    FlowDocument flowDoc = new FlowDocument(para);
    this.Document = flowDoc;
}
Run Code Online (Sandbox Code Playgroud)

When in write in Visual Studio "item.XXX" I should get the properties from my entitiy like .FirstName or .LastName. I do not know wether dataObjects is an IEnumerable or IOrder etc... it must be generic!

How can I get the real properties form item ? Only with Reflection?

Dan*_*Tao 7

Oded是对的,似乎(对他或我来说)没有任何意义来尝试使这种方法通用.您正在尝试对其功能实际上特定于几种类型的方法进行泛化.

现在,也就是说,似乎该函数的大部分与您想要访问的此属性无关.那么为什么不将它分成两部分:可以泛化的部分,以及不能部署的部分:

像这样的东西:

void BindElements<T, TProperty>(IEnumerable<T> dataObjects,
                                Func<T, TProperty> selector)
{
    Paragraph para = new Paragraph();

    foreach (T item in dataObjects)
    {
       // Notice: by delegating the only type-specific aspect of this method
       // (the property) to (fittingly enough) a delegate, we are able to 
       // package MOST of the code in a reusable form.
       var property = selector(item);

       InlineUIContainer uiContainer = this.CreateElementContainer(property)
       para.Inlines.Add(uiContainer);
    }

    FlowDocument flowDoc = new FlowDocument(para);
    this.Document = flowDoc;
}
Run Code Online (Sandbox Code Playgroud)

然后你处理特定类型的重载,例如,IPerson可以重用这个代码(我怀疑可能是你在所有代码重用之后的代码):

public void BindPeople(IEnumerable<IPerson> people)
{
    BindElements(people, p => p.FirstName);
}
Run Code Online (Sandbox Code Playgroud)

...然后IOrder:

public void BindOrders(IEnumerable<IOrder> orders)
{
    BindElements(orders, o => p.OrderNumber);
}
Run Code Online (Sandbox Code Playgroud)

...等等.