c# - Can TKey be inferred? -


this question has answer here:

i've created validator checks ilist<t> duplicates. came following implementation:

namespace consoleapplication1 {     class program     {         static void main(string[] args)         {             var bar = new foo() {bar = "buzz"};             var list = new list<foo>() { }; //foo has property named bar of type string             var validator = new validator<foo, string>(x => x.bar); //i have specify type of bar             validator.isvalid(list);         }     } }  public class foo {     public string bar { get; set; } }  public class validator<t, tkey> {     private readonly func<t, tkey> _keyselector;      public validator(func<t, tkey> keyselector)     {         _keyselector = keyselector;     }      public bool isvalid(ilist<t> list)     {         if (list != null && list.count > 0)         {             if (list.groupby(_keyselector).any(g => g.count() > 1))             {                 return false;             }         }          return true;     } } 

but don't how has used: have specify type of bar during construction.

the question can somehow skip tkey when initializing validator? can somehow inferred?

you can use generic extension method, requires separate static class. generic methods can derive t-types parameters.

here how:

public static class extensions {     public static validator<t, tkey> getvalidatorfor<t, tkey>(this list<t> list, func<t, tkey> getter) t : class     {         return new validator<t, tkey>(getter);     } } 

and can use this:

var list = new list<foo>(); var validator = list.getvalidatorfor(x => x.bar); 

Comments

Popular posts from this blog

.net - Bulk insert via Dapper is slower than inserting rows one-by-one -

shared memory - gstreamer shmsrc and shmsink with h264 data -

python - Error importing VideoFileClip from moviepy : AttributeError: 'PermissionError' object has no attribute 'message' -