我有这样的结构:
public readonly struct SomeStruct<T1, T2>
{
private readonly object _ref;
public SomeStruct(T1 value)
{
_ref = value;
}
public SomeStruct(T2 value)
{
_ref = value;
}
public SomeStruct<U1, T2> Select<U1>(Func<T1, U1> mapLeft){ // logic... }
public SomeStruct<T1, U2> Select<U2>(Func<T2, U2> mapRight) { // logic... }
}
我尝试使用这样的方法:
SomeStruct<int, string> someStruct = new SomeStruct<int, string>("test");
SomeStruct<bool, string> newStruct = someStruct.Select<bool>(x => true);
要么
SomeStruct<int, string> someStruct = new SomeStruct<int, string>(111);
SomeStruct<int, bool> newStruct = someStruct.Select<bool>(x => true);
但是我遇到了错误:错误下列方法或属性之间的调用不明确:'SomeStruct.Select(Func)'和'SomeStruct.Select(Func)'
您需要明确指定类型,因为编译器无法推断lambda表达式的输入类型。例如,
SomeStruct<int, string> someStruct = new SomeStruct<int, string>(111);
SomeStruct<int, bool> newStruct = someStruct.Select<bool>((int x) => true);
为什么会这样呢?
你打电话someStruct.Select<bool>(x => true)
。someStruct的类型是SomeStruct<int, string>
。因此,如果Select<bool>
您具有以下方法,则someStruct
:
public SomeStruct<bool, string> Select<bool>(Func<int, bool> mapLeft) {}
public SomeStruct<int, bool> Select<bool>(Func<string, bool> mapRight) {}
因此,您的lambda表达式x => true
可以推断为Func<int, bool>
或Func<string, bool>
。因此,您需要为输入参数指定int
或string
,以避免产生歧义。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句