c# 类型转换函数代理封装
Converter<TInput,TOutput> Delegate
Represents a method that converts an object from one type to another type.
public delegate TOutput Converter<in TInput,out TOutput>(TInput input);
- TInput
The type of object that is to be converted.
- TOutput
The type the input object is to be converted to.
- input
The object to convert.
- Inheritance
Examples
This section contains two code examples. The first demonstrates the Converter<TInput,TOutput> delegate with the ConvertAll method of the Array class, and the second demonstrates the delegate with the <xref:System.Collections.Generic.List`1.ConvertAll``1*> method of the List<T> generic class.
Example 1
The following code example defines a method named PointFToPoint
that converts a PointF structure to a Point structure. The example then creates an array of PointF structures, creates a Converter<PointF, Point>
delegate (Converter(Of PointF, Point)
in Visual Basic) to represent the PointFToPoint
method, and passes the delegate to the ConvertAll method. The ConvertAll method passes each element of the input list to the PointFToPoint
method and puts the converted elements into a new list of Point structures. Both lists are displayed.
using System;
using System.Drawing;
using System.Collections.Generic;
public class Example
{
public static void Main()
{
// Create an array of PointF objects.
PointF[] apf = {
new PointF(27.8F, 32.62F),
new PointF(99.3F, 147.273F),
new PointF(7.5F, 1412.2F) };
// Display each element in the PointF array.
Console.WriteLine();
foreach( PointF p in apf )
Console.WriteLine(p);
// Convert each PointF element to a Point object.
Point[] ap = Array.ConvertAll(apf,
new Converter<PointF, Point>(PointFToPoint));
// Display each element in the Point array.
Console.WriteLine();
foreach( Point p in ap )
{
Console.WriteLine(p);
}
}
public static Point PointFToPoint(PointF pf)
{
return new Point(((int) pf.X), ((int) pf.Y));
}
}
/* This code example produces the following output:
{X=27.8, Y=32.62}
{X=99.3, Y=147.273}
{X=7.5, Y=1412.2}
{X=27,Y=32}
{X=99,Y=147}
{X=7,Y=1412}
*/