我会试着用一个例子来解释我的问题:
class V<T>
{
public readonly Func<T> Get;
public readonly bool IsConstant;
V(Func<T> get, bool isConstant)
{
Get = get;
IsConstant = isConstant;
}
public static implicit operator V<T>(T value)
{
return new V<T>(() => value, true);
}
public static implicit operator V<T>(Func<T> getter)
{
return new V<T>(getter, false);
}
}
void DoSomething<T>(V<T> v)
{
//...
}
void Main()
{
DoSomething<string>("test"); // (1) type inference is not working
DoSomething<string>((V<string>)(() => "test")); // (2) implicit operator does not work
}
在方法中Main
,我有两种情况:
- 我必须明确指定通用参数
<string>
方法DoSomething
. - 在这里,我必须添加显式转换
(V<string>)
,隐式运算符似乎不起作用。
为什么需要这样做?编译器正在考虑哪些备选方案,因此无法选择正确的方式?
最佳答案
你的第二个问题是为什么从()=>""
隐式转换至 V<string>
没有成功,即使()=>""
可转换为 Func<string>
和 Func<string>
可转换为 V<string>
.
同样,我不知道如何回答“为什么不呢?”问题,但我确实知道如何回答“规范的哪一行表明编译器应该拒绝此代码?”这个问题。相关行是:
First, if required, performing a standard conversion from the source type to the operand type of the user-defined or lifted conversion operator.
注意这里有个小错误;这应该表示从源表达式 执行标准转换。源表达式可能没有类型。我相信在我离开团队之前,我已经向规范维护者说明了这一点,所以希望这会在下一版本中得到修复。
无论如何,现在应该清楚这里发生了什么。没有从 lambda 到委托(delegate)类型的标准转换,因此用户定义的转换被转换解析算法分类为不适用。
关于c# - 为什么类型推断和隐式运算符在以下情况下不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14115059/