C# Combine methods by passing in field type?
I wasn't sure how to title this question correctly but here is what i'm trying to do.
Say I have a class Customer that has an ID, firstName, and lastName field. Now say I have a list of customers and I want to write one method that will 开发者_StackOverflowwrite ID, firstName, OR lastName to the console depending on which one I specify.
In essense, I would like to write one method that accepts the field I would like to print out instead of writing three seperate methods to print out each field type.
I know I have read about how to do this in C# over the past few days but my brain is on overload and it is slipping my mind....
Any help would be appreciated.
public void PrintCustomer<T>(Customer c, Func<Customer, T> func)
{
Console.WriteLine("{0} , {1}", c.ID, func(c));
}
Usage:
PrintCustomer(myCustomer, c => c.FirstName);
OR
PrintCustomer(myCustomer, c => c.LastName);
Use an Enum as an argument? Each enum value is a different target field...
This is really just a comment on BFree's answer but I wanted to have syntax highlighting...
The type of the return value can be hidden from client code using the following signature. I would consider this an improvement.
public static void PrintCustomer(Customer c, Func<Customer, string> func)
{
Console.WriteLine("{0} , {1}", c.ID, func(c));
}
精彩评论