0

我是泛型新手,需要一些帮助。

我想为所有“变压器”类创建一个接口来实现。要成为“变形金刚”,该类必须至少包含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();
    }
}
4

4 回答 4

2

也许在接口定义中添加泛型参数:

public interface ITransformer<T>
{
     T MapTo(T t); 
}

并实现您需要的所有映射:

public class Transformer : ITransformer<XmlDocument>, ITransformer<UIPerson>
于 2012-07-25T12:19:09.690 回答
1

尝试这个:

public interface ITransformer<T>
{
    T MapTo(T t);
}

然后当你实现你的接口时,你的类看起来像:

public class Transformer : ITransformer<XmlDocument>
{
    public XmlDocument MapTo(XmlDocument t)
    {
        throw new NotImplementedException();
    }
}
于 2012-07-25T12:15:47.600 回答
1

您需要使ITransformer 接口通用。所以,你想要这个:

public interface ITransformer<T>
{
    public T MapTo(T t);
}

然后,在实现接口时,类可以将它们希望使用的类的类型参数传递给接口:

public class Transformer : ITransformer<XmlDocument>
{
    public XmlDocument MapTo(XmlDocument t)
    {
        //...
    }
}

编辑:正如下面的lazyberezovsky所说,没有什么能阻止你多次实现同一个接口:

public class Transformer : ITransformer<XmlDocument>, ITransformer<UIPerson>

当然,它必须提供XmlDocument MapTo(XmlDocument t)和的实现UIPerson MapTo(UIPerson t)

于 2012-07-25T12:16:02.687 回答
0

我认为您要做的是具有以下界面:

public interface ITransformer<TEntity> {
    public TEntity MapTo(TEntity entity);
}
于 2012-07-25T12:16:57.523 回答