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;
}
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?
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:
Something like this:
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):...then for
IOrder
:...and so on.
Adding to Dan's answer,
Func<T, TProperty> selector
merely says thatselector
is an identifier for a method that takes in a parameter of typeT
and has a return type ofTProperty
. So, a valid method that could be passed intoBindElements
as a second parameter would be, for example,In this case,
TProperty
would be astring
andT
wouldIPerson
. You can then callBindElements
like sowhere myPersonCollection can just be whatever
List<T>
you were referring to. Then moving on to the foreach loopproperty
is being set to an object of typeTProperty
, which in the case ofCreatePersonElement
is astring
. If astring
doesn't work for you, just change the return type of the method to be whateverCreateElementContainer
is accepting as its parameter.You would then have one of these methods to pass into the second parameter for
BindElements
for each type you want to support (i.e.ICustomer
,IOrder
).If you add a constraint to the generic type (say it has to implement the
IPerson
interface), you can use any methods defined on the interface:If
IPerson
definesFirstName
andLastName
peroperties, you can use them withT
.See the link for the different types of generic constraints possible.
I would read http://msdn.microsoft.com/en-us/library/d5x73970.aspx and think about Oded's answer again.