通用类型,使用接口的不同泛型类型?
问题描述:
我对泛型相当陌生,而且我在理解部分工作方式方面遇到了一些麻烦,并且无法按照自己的方式工作。通用类型,使用接口的不同泛型类型?
到目前为止,我有这个;
public interface IObjectMapper
{
T MapObject<T>() where T : new();
}
public class CustomObjectMapper : IObjectMapper
{
T IObjectMapper.MapObject<T>()
{
T retObject = new T();
//do stuff......
}
}
这工作正常,但我不明白“T:new()”在做什么。有人可以解释吗?此外,对于我的第二个问题 - 我想要第二个方法称为DemapObject,它接受2个参数,来自对象的同一个泛型类型T,然后不同泛型类型的U - U也应该是返回类型。
public interface IObjectMapper
{
T MapObject<T>() where T : new();
U DemapObject<T, U>() ??????? what goes here?
}
最后,一旦我得到DemapObject的接口方法完成 - 它是如何从实现类中调用的?
public class CustomObjectMapper : IObjectMapper
{
NameValueCollection IObjectMapper.DempaObject<T, NameValueCollection>()
{
//is this right????????????
}
}
答
where T: new()
要求作为T
任何类型应该实现默认(参数的构造函数) 。否则就不可能创建一个T类的实例。
对于你的最后一个问题:你不能做一个通用方法的专门实现。但是你可以做一个专门的接口实现。考虑一下:
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();
而我还没有理解你的第二个问题,你能否详细说明一下?
答
“其中T:”将在T上设置约束。在这种情况下的约束是“new()”。这意味着泛型类型T必须有一个不带参数的构造函数。
可以叠加,其中在同类型的条款:
class MyClass<T> where T : class, new() { }
或不同的类型:
class MyClass<T,U>
where T : class, new()
where U : IMyInterface
{
}
+0
+1部分和如此快速地回答。谢谢! – WesleyJohnson 2009-11-18 07:44:34
我不确定我是否正确地问了这个问题,但看着你的代码,我想你已经解决了它。我试图创建一个映射对象的接口 - 有点像ORM的东西。 因此,基本上DemapObject方法将采用一个通用对象并去除它的值,将它们填入返回类型并将其吐出。 因此,一个实现可能具有返回类型的DataTable用于DemapObject,而另一个实现可能具有返回类型NameValueCollection。然而,另一个可能会返回一个字符串,其中包含所有值,以便查询字符串。 – WesleyJohnson 2009-11-18 07:34:44