有没有办法实现通用类型的扩展方法,该方法接受另一种类型的 Func 参数?
例如,类似于以下的用法:
myFirstObject.Extension<myOtherObject>( other => other.Prop );
或者使用更复杂的 Func:
myFirstObject.Extension<myOtherObject>( other => other.Prop > 2 && other.Prop < 15 );
我发现了一些相关问题,例如 this one ,但就我而言,我也需要扩展方法中的泛型类型。
这是我想到的:
public static bool Extension<TSource, TIn, TKey>(this TSource p_Value, Expression<Func<TIn, TKey>> p_OutExpression)
{ return true; }
但是,当我尝试使用它时,它没有考虑第二种类型。
我错过了什么吗?
最佳答案
看看这个:
s => s.Length;
编译器如何知道是否 s
是 string
或s
是一个数组或具有 Length
的其他类型属性(property)?它不能,除非你给它一些信息:
(string s) => s.Length;
哦,我们开始了。所以现在,试试这个:
myFirstObject.Extension((myOtherObject o) => o.Prop > 2 && o.Prop < 15);
这会起作用,因为你已经告诉编译器它应该用于 TIn
。 ,并且它可以找出 TKey
的用途根据表达式。
关于linq - 具有其他类型泛型 Func 参数的扩展方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17869106/