方法参数接受一个模型并返回不同模型的通用方法

时间:2018-08-02 05:38:09

标签: c#

我正在尝试编写通用的代码,其中Method接受模型作为参数,然后根据该参数返回不同的模型。

调用方法。

 UserModelApi model = (UserModelApi) GetModels(dto);

方法定义:

    private T GetModels<T>(T _dto)
    {
        T t = default(T);
        if (_dto.GetType() == typeof(UserDTO))
        {
            UserDTO dto = (UserDTO)(object)_dto;
            UserModelApi model = new UserModelApi()
            {
               ........
            };
            return (T)(object)model;
        }
        return t;
    }

但这不能像UserModelApi model = (UserModelApi)GetModels(dto);那样工作,除了模型(UserModelApi)以外,它是返回的UserDTO模型。

问题是我如何概括方法定义,使其接受一个模型作为参数但返回不同的模型?

2 个答案:

答案 0 :(得分:1)

要返回其他类型的实例,我们需要另一个通用类型参数。我们称之为TResult。对于映射,我们可以创建一个Mapper或使用名为AutoMapper的现有库:

  1. 获取Automapper NuGet软件包

  2. 更改方法,添加新的TResult参数并使用Automapper映射事物:

    // 'where class' constraint is required because we'll return null as default value
    private static TResult GetModels<T, TResult>(T dto) where TResult : class
    {
        if (dto != null)
        {
            try
            {
                TResult model = null;
    
                // here we check if the actual mapping exists in AM configuration
                var map = Mapper.Configuration.FindTypeMapFor<T, TResult>();
    
                if (map != null)
                {
                    model = Mapper.Map<T, TResult>(dto);
                }
                return model;
            }
            catch (Exception ex)
            {
               // log other errors here
            }
        }
        return default(TResult);
    }
    
  3. 在开始使用它之前,我们需要创建一个映射。类似于:

        Mapper.Initialize(c =>
        {
            c.CreateMap<UserDTO, UserModelApi>().ConvertUsing(f1 => new UserModelApi()
            {
                // add the mapping here
            });
        });
        Mapper.AssertConfigurationIsValid();
    

最后我们可以使用新方法:

UserModelApi model = GetModels<UserDTO, UserModelApi>(dto);

示例:https://dotnetfiddle.net/80jADT

答案 1 :(得分:0)

您可以创建扩展方法,并通过反射将值从对象手动复制到新对象。

{Element|Null*}