I would like to define a generic class in C#:
public class MyService<TModel>
{
public MyService(/*What to declare here?*/)
{
}
}
such that I can instantiate it like the following:
var service = new MyService<SomeModel>(m => m.SomeField);
where SomeField
is restricted to be a field of SomeModel
. Is this possible?
I know I can declare something similar for a method within the class but can't quite figure out how this can be done for constructors. For example, I can declare the following in MyService
:
public void SomeMethod<TMember>(Expression<Func<TModel, TMember>> member)
{
}
and be able to invoke it like this:
var service = new MyService<SomeModel>();
service.SomeMethod(m => m.SomeField);
and the compiler would complain if SomeField
wasn't actually a field of SomeModel
.
Aucun commentaire:
Enregistrer un commentaire