简体   繁体   中英

Func delegate as a constructor parameter

Trying to get my head round using delegates.

I have a class synchronise.cs takes two collections of different types and edits them. The collections are held in another other viewModel class. I've written a constructor which takes two Func delegates as parameters in synchronise.cs :

 public Synchronise(
     Func<IEnumerable<T> , IEnumerable<S>> MappingStoT,
     Func<IEnumerable<S>, IEnumerable<T>> MappingTtoS )
 {

 }

I'm then trying to new up a Synchronise object in my ViewModel and pass two methods with the collections as parameters:

this.mySynchroniser = new Synchronise<IBindableData, object>(MappingStoT(CollectionA), MappingTtoS(CollectionB));

Finally my two methods:

 public IEnumerable<CollectionA> MappingStoT(IEnumerable<CollectionB> CollectionForEdit)
 {
     var query = blah blah
     return query;
 }

 public IEnumerable<CollectionB> MappingTtoS(IEnumerable<CollectionA> CollectionForEdit)
 {
      var query = Blah blah
      return query;
 }

I'm getting not assignable to parameter type on my new Synchronizer . Am I going about this the right way?

Your constructor expects Func s, and not the result of a method call. Try this:

class CollectionA { }
class CollectionB { }

class Synchronise<T, S>
{
    public static Synchronise<CollectionB, CollectionA> Create()
    {
        return new Synchronise<CollectionB, CollectionA>(MappingStoT, MappingTtoS);
    }

    public Synchronise(Func<IEnumerable<T>, IEnumerable<S>> MappingStoT, Func<IEnumerable<S>, IEnumerable<T>> MappingTtoS)
    {

    }
    public static IEnumerable<CollectionA> MappingStoT(IEnumerable<CollectionB> CollectionForEdit)
    {
        return null;
    }

    public static IEnumerable<CollectionB> MappingTtoS(IEnumerable<CollectionA> CollectionForEdit)
    {
        return null;
    }
}

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