I have some objects like user, address and so on, and Im converting them to business objects using extension methods:
public static UserModel ToPresentationForm(this User pUser)
{
return new UserModel
{
...
map data
...
};
}
Also I need to convert strongly t开发者_运维百科yped collections and usually I have the following code:
public static List<UserModel> ToPresentationForm(this List<User> pUserColl)
{
return pUserColl.Select(x => x.ToPresentationForm()).ToList();
}
I was thinking, what if I add some interface, like IPresentationForms and will be able to use it, to write method like
public static List<T> ToPresentationForm(this List<IPresentationForms> pTemplate)
{
return pUserColl.Select(x => x.ToPresentationForm()).ToList();
}
Not sure how to provide parameter to method type to make it generic. So the actual question is, how to do that.
P.S. Im using C# 4.0
Unfortunately since there is likely no relationship between User
and UserModel
, there is no way to create an interface to do what you want.
On the other hand, let's say that User
and UserModel
both implement the IUser
interface. Then you could have an interface like this:
interface IPresentationForms<T>
{
T ToPresentationForm();
}
And you could define User
like this:
class User: IUser, IPresentationForms<IUser>
{
public IUser ToPresentationForm()
{
return new UserModel(...);
}
.... // implement IUser
}
That could enable you to define ToPresentationForm
something like this:
public static List<T> ToPresentationForm<T>(this IEnumerable<T> pTemplate)
where T : IPresentationForms<T>
{
return pTemplate.Select(x => x.ToPresentationForm()).ToList();
}
That's a lot of work to do to avoid a few extra methods.
精彩评论