gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:14:34 28 4
gpt4 key购买 nike

我在我的应用程序中使用 .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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com