我是泛型新手,需要一些帮助。
我想为所有“变压器”类创建一个接口来实现。要成为“变形金刚”,该类必须至少包含T mapTo<T>(T t)
.
以下是我想如何使用 TRANSFORMERS:
重载一些方法……太棒了!似乎很容易!
public class Transformer : ITransformer
{
public Transformer(IPerson instance)
{
}
public XmlDocument mapTo(XmlDocument xmlDocument)
{
// Transformation code would go here...
// For Example:
// element.InnerXml = instance.Name;
return xmlDocument;
}
public UIPerson maptTo(UIPerson person)
{
// Transformation code would go here...
// For Example:
// person.Name = instance.Name;
return person;
}
}
让我们使用泛型来定义接口:
好主意!
public interface ITransformer
{
T MapTo<T>(T t);
}
问题:
如果我在接口中使用泛型,我的具体类实际上被迫实现以下内容:
public T MapTo<T>(T t)
{
throw new NotImplementedException();
}
这使班级看起来很丑陋
public class Transformer : ITransformer
{
public Transformer(IPerson instance)
{
}
public XmlDocument MapTo(XmlDocument xmlDocument)
{
// Transformation code would go here...
// For Example:
// element.InnerXml = instance.Name;
return xmlDocument;
}
public UIPerson MapTo(UIPerson person)
{
// Transformation code would go here...
// For Example:
// person.Name = instance.Name;
return person;
}
public T MapTo<T>(T t)
{
throw new NotImplementedException();
}
}