C #: delegate with shared

Please focus on

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

inside the codes below.

Converter<PointF, Point> contains two type parameters? Why does 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)); } } 
+4
source share
4 answers

"The converter contains two parameters of the type: How to find out the parameters of the method passed to the Converter () constructor?"

This is how the converter delegate is defined. Does the converter contain two types of parameters? How to find out the parameters

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

Once you create an instance of this delegate by passing the method that follows with this signature (taking a value of one type and converting it to a value of another type), you also define a method parameter.

So, my answer when creating this converter is that you very well know the specific types for the universal converter method and the type of the parameter of the method.

+2
source

Well, in fact, you only have one parameter that is passed to the converter, the output type of which is the return type of your converter, and the input type is the input type of your argument, and the instance is the argument itself.

+2
source

I'm not quite sure what you are asking here. But the expression can be written like this:

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

Where p is the point you want to convert. I'm not sure if this will help you in any way, but it might be a little clearer what it does.

Update

This: <PointF, Point> does not mean that the method accepts two parameters. This means that it must take one parameter (type PointF) and return an object of type Point.

+2
source

Adding to other answers to shorten everything, you can also write:

 List<Point> lp = lpf.ConvertAll(PointFToPoint); 

If you do not need this PointFToPoint method elsewhere, you can also remove the entire public static Point PointFToPoint(PointF pf) method and use the built-in delegate instead:

 List<Point> lp = lpf.ConvertAll((delegate PointF pf) { return new Point(((int) pf.X), ((int) pf.Y)); }); 

And if you're in .NET 3.5, you can shorten this with lambda:

 List<Point> lp = lpf.ConvertAll(pf => new Point(((int) pf.X), ((int) pf.Y))); 
+2
source

Source: https://habr.com/ru/post/1300149/


All Articles