从C#泛型对象获取属性 [英] Get Property from a generic Object in C#

查看:975
本文介绍了从C#泛型对象获取属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看看这段代码,请:

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;
}

当在Visual Studio写item.XXX我应该得到的属性从我entitiy像.FirstName或.LastName。我不知道羯羊数据对象是一个IEnumerable或IOrder等...它必须是通用的吧!

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!

我怎样才能得到真正的性质形成项目?只有反思?

推荐答案

俄德是正确,它似乎并没有(对他或我)作出任何有意义的尝试,使这个方法通用的。您正在尝试泛化其功能实际上是专门针对几类的方法。

Oded is right, it doesn't seem (to him or me) to make any sense to try and make this method generic. You are trying to genericize a method whose functionality is actually specific to a few types.

现在,这么说,看来的的的功能是独立的,你要访问这个属性。那么,为什么不把它拆分成两部分:即可以泛型化,而哪些不能:

Now, that said, it seems the bulk of the function is independent of this property you want to access. So why not split it into two parts: that which can be genericized, and that which can't:

事情是这样的:

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;
}



那么你的重载处理特定类型,例如, IPerson ,可重用的代码(我怀疑可能是你是什么毕竟沿代码重用):

Then your overloads dealing with specific types, e.g., IPerson, can reuse this code (which I suspect may be what you were after all along—code reuse):

public void BindPeople(IEnumerable<IPerson> people)
{
    BindElements(people, p => p.FirstName);
}



...然后 IOrder

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



...等。

...and so on.

这篇关于从C#泛型对象获取属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆