带有action <t1,t2>的字典,其中T是作为参数的列表

时间:2018-10-23 14:04:11

标签: c#

是否有一种解决方案,使字典能够引用方法,而这些方法接收两个作为列表的参数?我遇到多个错误:

字典未编译: “使用泛型Dictionary <>需要两个参数” “无效的表达式术语'字符串'” “;预期” ...

class CTARules
{
    public static void TwentyFiftyMA(List<Data_Raw> myRawData, List<Data_Result> myResultData)
    {
        //do stuff
    }
    public static void TwentyHundredMA(List<Data_Raw> myRawData, List<Data_Result> myResultData)
    {
        //do stuff
    }
}

Dictionary<string, Action<List<Data_Raw>,List<Data_Result>> rulesDictionary = new Dictionary<string, Action> { };
        rulesDictionary.Add("twentyFifty", CTARules.TwentyFiftyMA);
        rulesDictionary.Add("twentyHundred", CTARules.TwentyHundredMA);

    public class Data_Raw
{
    public DateTime DateDataRaw { set; get; }
    public double PercentageReturnsRaw { set; get; }

    public Data_Raw(DateTime _dateDataRaw, double _percentageReturnsRaw)
    {
        DateDataRaw = _dateDataRaw;                     //1
        PercentageReturnsRaw = _percentageReturnsRaw;
    }
}


//For output result data list:
class Data_Result
{
    public DateTime DateData { set; get; }
    public double PercentageReturns { set; get; }

    public Data_Result(DateTime _dateData, double _percentageReturns)
    {
        DateData = _dateData;                     //1
        PercentageReturns = _percentageReturns;
    }


}

2 个答案:

答案 0 :(得分:1)

不能将Dictionary<string, Action<List<Data_Raw>,List<Data_Result>>>实例化为Dictionary<string, Action>-您应该实例化所需的确切类型。 另外,这是使用var关键字的经典方法:

var rulesDictionary = new Dictionary<string, Action<List<Data_Raw>,List<Data_Result>>>();

答案 1 :(得分:1)

您会遇到语法错误,例如缺少右尖括号>以及在字典构造函数上使用错误的类型。

这是一个完整的mcve,.net Fiddle

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        Dictionary<string, Action<List<Data_Raw>, List<Data_Result>>> rulesDictionary = new Dictionary<string, Action<List<Data_Raw>, List<Data_Result>>>();
        rulesDictionary.Add("twentyFifty", CTARules.TwentyFiftyMA);
    }
}

class Data_Raw
{
}

class Data_Result
{
}

class CTARules
{
    public static void TwentyFiftyMA(List<Data_Raw> myRawData, List<Data_Result> myResultData)
    {
    //do stuff
    }

    public static void TwentyHundredMA(List<Data_Raw> myRawData, List<Data_Result> myResultData)
    {
    //do stuff
    }
}