简体   繁体   中英

What is best way to create converter from function?

I want to apply func object as converter like this:

Func<int, double> f = x => x / 2.5;
Converter<int, double> convert = f;
List<double> applied_list = new List<int>(){1, 2, 3}.ConvertAll(convert);

Compiler gives me such message:

Error CS0029 Cannot implicitly convert type 'System.Func' to 'System.Converter'

What is best way to use function as converter?

There are three options here. In my preferred order, they are:

  • Start using LINQ instead of ConvertAll :

     List<double> appliedList = new List { 1, 2, 3 }.Select(f).ToList(); 
  • Create a converter to start with:

     Converter<int, double> converter = x => x / 2.5; List<double> appliedList = new List { 1, 2, 3 }.ConvertAll(converter); 
  • If you really, really must, create a converter from the function using a delegate creation expression:

     Func<int, double> f = x => x / 2.5; Converter<int, double> converter = new Converter<int, double>(f); List<double> appliedList = new List { 1, 2, 3 }.ConvertAll(converter); 

The last option creates a delegate that just wraps the original one.

使用var converter = new Converter<int, double>(f) ,或者简单地使用Select()进行映射:

var appliedList = new List<int>(){ 1, 2, 3 }.Select(f);

If you prefer to use .ConvertAll instead of .Select then implement a simple workaround to convert Func to delegate Converter in following way:

    Func<int, double> f = x => x / 2.5;
    Converter<int, double> convert = x => f(x);
    List<double> applied_list = new List<int>() { 1, 2, 3 }.ConvertAll(convert);

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