Generic type in, different generic type out using interfaces?
I'm fairly new to generics and I'm having some trouble understanding parts of how they work and 开发者_如何学编程also failing to get it to work the way I want.
So far, I have this;
public interface IObjectMapper
{
T MapObject<T>() where T : new();
}
public class CustomObjectMapper : IObjectMapper
{
T IObjectMapper.MapObject<T>()
{
T retObject = new T();
//do stuff......
}
}
This works fine, but I don't understand what "where T : new()" is doing. Can someone please explain? Also, for my second question - I want a second method called DemapObject that takes 2 parameters, the same generic type T from object and then a different generic type of U - U should also be the return type.
public interface IObjectMapper
{
T MapObject<T>() where T : new();
U DemapObject<T, U>() ??????? what goes here?
}
Finally, once I get the interface method for DemapObject done - how is it called from the implementation class?
public class CustomObjectMapper : IObjectMapper
{
NameValueCollection IObjectMapper.DempaObject<T, NameValueCollection>()
{
//is this right????????????
}
}
"where T :" will set a constraint on T. The constraint in this case is "new()". This means that the generic type T must have a constructor which takes no parameters.
You can stack where clauses on the same type:
class MyClass<T> where T : class, new() { }
or on different types:
class MyClass<T,U>
where T : class, new()
where U : IMyInterface
{
}
where T: new()
requires that any type used as T
should implement default (argument-less constructor). Otherwise it will be impossible to create an instance of T class.
For your last question: you can't make a specialized implementation of generic method. But you can make a specialized implementation of interface. Consider this:
public interface IObjectMapper<U> where U:new
{
T MapObject<T>(U arg) where T:new()
U DemapObject<T>(T arg);
}
public class CustomObjectMapper : IObjectMapper<NameValueCollection>
{
T MapObject<T>(NameValueCollection arg) where T:new(){
....
}
NameValueCollection DemapObject<T>(T arg)
{
....
}
}
IObjectMapper<NameValueCollection> mapper = new CustomObjectMapper();
And I haven't understood your second question, can you elaborate?
精彩评论