简体   繁体   中英

Why i can't use generic type with lamba expression?

Why i can't use the following lambda inside a method? Under what circumstances is allowed to use generic types?

For example i know that i can use generics inside a class:

//Valid
public class GenericList<T>
{
    void Add(T input) { }
}

but i can't in the following code:

 //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) => { ... };
 }

** I don't think it's framework specific but just in case i use 3.5

You need to expose the TypeParameter in the method signature like this:

private void Timer1_Tick<T>(object sender, EventArgs e)
 {
     Action<List<T>, List<T>> syncLists = (l1, l2) => { ... };
 }

Otherwise there is no way for the client to specify how the method should behave, and what type is to be acted upon.

An alternative technique, more appropriate in some circumstances, would be to expose the Type Parameter in the class signature thus:

public class TestClass<T> {
    private void Timer1_Tick(object sender, EventArgs e)
     {
         Action<List<T>, List<T>> syncLists = (l1, l2) => { ... };
     }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM