Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: delegate with generic

Tags:

c#

Please focus on

List<Point> lp = lpf.ConvertAll( 
                new Converter<PointF, Point>(PointFToPoint));

inside the codes below.

Converter<PointF, Point> holds two type parameters? Why PointFToPoint just hold one parameter?

public class Example
{
    public static void Main()
    {
        List<PointF> lpf = new List<PointF>();

        lpf.Add(new PointF(27.8F, 32.62F));
        lpf.Add(new PointF(99.3F, 147.273F));
        lpf.Add(new PointF(7.5F, 1412.2F));

        Console.WriteLine();
        foreach( PointF p in lpf )
        {
            Console.WriteLine(p);
        }

        List<Point> lp = lpf.ConvertAll( 
            new Converter<PointF, Point>(PointFToPoint));

        Console.WriteLine();
        foreach( Point p in lp )
        {
            Console.WriteLine(p);
        }
    }

    public static Point PointFToPoint(PointF pf)
    {
        return new Point(((int) pf.X), ((int) pf.Y));
    }
}
like image 601
Ricky Avatar asked Feb 28 '23 16:02

Ricky


1 Answers

" Converter holds two type parameters? How do I know the parameters of the method being passed on to the constructor of Converter()? "

This is how converter delegate is defined. Converter holds two type parameters? How do I know the parameters of the

public delegate TOutput Converter<TInput,TOutput>(TInput input);

As soon as you create instance of this delegate by passing a method which abides with this signature (accepting value of one type and converting it into value of another type), you define the parameter of the method also.

So, my answer is while creating this converter you very well know the concrete types for the generic Converter method, and the Type of the method parameter as well.

like image 93
Manish Basantani Avatar answered Mar 06 '23 22:03

Manish Basantani