具有具体类覆盖的通用扩展方法

问题描述

我有一个第三方 DLL,它返回 CustomersOrders 等对象。我将它们称为 Your Entities。它们确实有一个通用的 IYourEntity 接口,因此我可以将其用作源约束。

我想创建一个通用的转换扩展方法,用一些简化且更易于维护的代码将所有这些不同的第三方实体转换为 My Entities

....但是我不知道如何制作一个通用的扩展方法,它会为每个类的特定转换调用具体的扩展方法。

将我的代码的一些主要方面放在下面,但您可以使用 here 进行完整的演奏。

是的,我可能表现出我对如何做到这一点有点无能为力,并且可能试图结合不同的概念。任何指点都非常感谢,因为我已经连续几天一直在打头,需要一条生命线:)

public interface IYourEntity
{
    int Id
    {
        get;
        set;
    }
}

public interface IConvertToMyEntity<TYourEntity,TMyEntity>
    where TYourEntity : class,IYourEntity,new()
    where TMyEntity : class,IMyEntity,new()
{
    TMyEntity ToMyEntity(TYourEntity yourEntity);
}

public static class ExtensionMethods
{
    private static IMyEntity ToMyEntity(this IYourEntity yourEntity)
    {
        return new MyEntity1();
    }

    public static List<IMyEntity> ToMyEntityList(this List<IYourEntity> lstYourEntities)
    {
        return lstYourEntities.ConvertAll(q => q.ToMyEntity());
    }
}

public class YourEntity1 : IYourEntity,IConvertToMyEntity<YourEntity1,MyEntity1>
{
    public int Id
    {
        get;
        set;
    }

    public string YourEntityName
    {
        get;
        set;
    }

    public MyEntity1 ToMyEntity(YourEntity1 yourEntity)
    {
        return new MyEntity1()
        {Id = yourEntity.Id,MyEntityName = yourEntity.YourEntityName,CreatedOn = DateTime.UtcNow};
    }

    public List<MyEntity1> ToMyEntityList(List<YourEntity1> lstYourEntities)
    {
        return lstYourEntities.ConvertAll(q => ToMyEntity(q));
    }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)