c# - 从扩展方法中消除可推断的泛型类型参数

标签 c# .net generics automapper

我在我的应用程序中使用 .NET 映射库 AutoMapper,我有一个像这样的通用扩展方法:

public static T2 Map<T1, T2>(this T1 o)
{
    return Mapper.Map<T1, T2>(o);
}

...

var nc = new NonCustomer();
Customer c = nc.Map<NonCustomer, Customer>();

有什么方法可以从扩展方法中删除 T1 泛型参数以便推断吗?导致这样的调用:

var nc = new NonCustomer();
Customer c = nc.Map<Customer>();

最佳答案

您不需要为 T1 参数使用通用版本。

你只需要把它改成object:

public static TDest Map<TDest>(this object o)
{
    // todo check o is not null
    return (TDest) Mapper.Map(o, o.GetType(), typeof (TDest));
}

如果你使用的是AutoMapper v2及以上版本,你可以这样写:

public static TDest Map<TDest>(this object o)
{
    return Mapper.Map<TDest>(o);
}

关于c# - 从扩展方法中消除可推断的泛型类型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11793269/

相关文章:

vb.net - 如何在 VB.NET 中创建通用属性?

c# - 如何使用 LINQ 查找 DataGridView 行?

c# - 如何找到当前用户具有 WriteProperty 访问权限的 ActiveDirectory 中的所有组?

.net - 单个或多个锁定对象

c# - 我应该使用 '==' 进行 .NET 本地化字符串比较吗?

java - 通用类型数组的可能方法?

c# - Elasticsearch嵌套数组的多个过滤条件

c# - 任何c#应用程序都可以在linux上运行吗

c# - 为什么 (object)0 == (object)0 不同于 ((object)0).Equals((object)0)?

swift - 为什么在 Swift 中对泛型协议(protocol)的元组进行类型别名允许我将其视为非泛型协议(protocol)?