Home > Enterprise >  Call a function with conditions in argument
Call a function with conditions in argument

Time:11-07

I am trying to use <TKey> in a function. I don't know how to use it properly as I discovered that recently.

Here is what I tried :

private void filterContour()
{
    if (this.geometryRepToDraw.Profile.Famille == "FLAT")
    {
        filterContour2(x => x[0].Face == 0);
    }
    else
    {
        filterContour2(x => x[0].Face == 0 || x[0].Face==1);
    }
}
private void filterContour2<TKey>(Func<List<Contour>, TKey> selector)
{
    this.internalContours = this.internalContours.Where(selector).ToList();
}

But cannot decompile, as I have the error cannot convert from <List<Contour>,Tkey> to <List<Contour>,bool>

For information, this.internalContours is a List<List<Contour>>

I also tried to replace Func<List<Contour>, TKey> by Func<List<Contour>, bool>, but error is when calling the function (and I don't think this is the good one)?

CodePudding user response:

In C# <TKey> signifies that a generic type (labeled 'TKey') is attributed to the function (usually somewhere in the funciton signature). This allows you, to write one function definition for multiple types, unlike in function overloading where you would have to write a definition for each overloaded type. Since the compiler has no way of knowing what kind of type you might pass to filterContour2<TKey>(...) it has no idea if it should be able to compile it or not.

In your case you are using a selector predicate with a return type of bool therefore you don't need a generic function. This should be what you are looking for:

private void filterContour2(Func<List<Contour>, bool> selector)
{
    this.internalContours = this.internalContours.Where(selector).ToList();
}

CodePudding user response:

I do not believe that you need to include the Func in the method signature.

Try changing the method signature to:

private void filterContour2(Func<List<Contour>, bool> selector)

I am taking a wild guess here…

  •  Tags:  
  • c#
  • Related