为什么我不能在方法中使用以下lambda?在什么情况下允许使用泛型类型?
例如,我知道我可以在一个类中使用泛型:
//Valid
public class GenericList<T>
{
void Add(T input) { }
}
但我不能使用以下代码:
//Not valid
private void Timer1_Tick(object sender, EventArgs e)
{
//Edit:
//As you can guess this is a timer event and Action is called
//only in this scope but possibly more than one time
//that's why i though to make it Action method.
//In the following line `Τ` is not recognized...
Action<List<T>, List<T>> syncLists = (l1, l2) => { ... };
}
**我不认为它是特定于框架的,但以防我使用3.5
答案 0 :(得分:3)
您需要在方法签名中公开TypeParameter,如下所示:
private void Timer1_Tick<T>(object sender, EventArgs e)
{
Action<List<T>, List<T>> syncLists = (l1, l2) => { ... };
}
否则,客户端无法指定方法的行为方式,以及要采取的操作类型。
在某些情况下更合适的替代技术是在类签名中公开Type参数:
public class TestClass<T> {
private void Timer1_Tick(object sender, EventArgs e)
{
Action<List<T>, List<T>> syncLists = (l1, l2) => { ... };
}
}