【发布时间】:2012-12-16 09:46:49
【问题描述】:
我会试着用一个例子来解释我的问题:
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>),隐式运算符似乎不起作用。
为什么需要这样做?编译器正在考虑哪些替代方案,因此无法选择正确的方式?
【问题讨论】:
-
我的猜测:(1)编译器在知道要转换为的类型之前不会进行隐式转换,并且
是必要的。 (2) lambda 表达式没有像 Func 这样的特定委托类型,编译器看不到潜在的隐式转换。 -
(1) 好的。 (2) 你是对的,转换为 (Func
) 就足够了。把它作为一个答案:) -
Main 不调用 DoSoemthing;它调用了其他一些方法 DumpValue。
标签: c# .net generics type-inference implicit-conversion