【发布时间】:2012-11-04 13:31:10
【问题描述】:
好吧,我一定是把标题弄错了。更多的代码,更少的文字:
public class Manager<T> where T : Control, new()
{
void Manage()
{
Do(t => IsVisible(t));
}
bool IsVisible(T t)
{
return t.Visible;
}
S Do<S>(Func<T, S> operation)
{
return operation(new T());
}
}
编译器对Do 很满意。它可以很容易地推断出T 类型。现在假设我有这个:
public static class Util
{
static void Manage()
{
Do(t => IsVisible(t)); //wiggly line here
}
static bool IsVisible<T>(T t) where T : Control
{
return t.Visible;
}
static S Do<S, T>(Func<T, S> operation) where T : Control, new()
{
return operation(new T());
}
}
编译器现在希望类型被显式类型化。这是我的想法:
在第一类中,T 很容易从 IsVisible 方法推断出来,该方法具有 T 重载,T 在 Manager 类中众所周知,没什么大不了的。但在第二种情况下,T 被指定为方法的通用约束,可能更难推断。好的。
但这也不起作用:
public static class Util
{
static void Manage()
{
Do(t => IsVisible(t)); //still wiggly line
}
static bool IsVisible(Control t)
{
return t.Visible;
}
static S Do<S, T>(Func<T, S> operation) where T : Control, new()
{
return operation(new T());
}
}
为什么编译器在最后一种情况下不推断
T?更重要的是,最后一个案例与第一个案例有何不同?在第一种情况下,编译器必须从
IsVisible方法推断它,然后一直返回检查T在包含IsVisible的类中是什么,而在最后一种情况下,它在IsVisible方法中很容易获得.所以我认为第三种情况比第一种更容易。
【问题讨论】:
标签: c# c#-4.0 type-inference generic-constraints