2

I am getting an error message that makes absolutely no sense to me!!

public class ChartInitializerBase
{
    #region Constructors
    public ChartInitializerBase(Func<object> retrieveData)
    {
        var Data = retrieveData;
    }
    #endregion
}

The idea of the constructor above is that I can pass different methods in to obtain data

For example, if I am displaying books I want to say

var intiialiser = new ChartInitializerBase(GetBooks(1234, 231))

If I am getting CDs I want to say

var intiialiser = new ChartInitializerBase(GetCDs(1234, 231, 34))

The parameters above are different, but both GetCDs and GetBooks would return a single object

In my exact situation I have

var chart = new DailyConsumptionChart(
            dataProvider.GetDataForDailyConsumptionChart("1", EUtilityGroup.Electricity, 321, 157, Convert.ToDateTime("01/01/2010"), Convert.ToDateTime("01/01/2010 23:30"), false));



 public class ProfileDataDashboardReportsDataProvider
 {
    #region Methods
    public object GetDataForDailyConsumptionChart(string idString, EUtilityGroup ug, int customerId, int userId, DateTime startDate, DateTime endDate, bool clockTime)
    {
        var mdp = new MeterDataProvider();
        var result = mdp.GetProfileDataForLocationForADay(idString, ug, customerId, userId, startDate, endDate, clockTime);

        return result;
    }
    #endregion
}

I have tried this as both a static an non static class as well as static and non static methods

It makes no difference which way I do it I still get Argument type object is not assignable to System.Func error

I am new to this kind of thing, please can someone suggest what I need to do to fix this?

I have seen this Parameter type not assignable when storing func in dictionary

But I dont think it helps me

I am not sure if I am tagging this in the correct areas please feel free to change if I am wrong

Paul


Try to pass lambda to your constructor, instead of the result of the method execution, like in the code example below.

var initialiser = new ChartInitializerBase(() => GetBooks(1234, 231));

Here you simply pass lambda with one statement - call to GetBooks method

Your constructor should be like

public ChartInitializerBase(Func<object> retrieveData) 
{ 
      var Data = retrieveData(); //here the method GetBooks will be called and data returned
}
4

1 回答 1

7

尝试将 lambda 传递给您的构造函数,而不是方法执行的结果,如下面的代码示例所示。

var initialiser = new ChartInitializerBase(() => GetBooks(1234, 231));

在这里,您只需使用一个语句传递 lambda - 调用 GetBooks 方法

你的构造函数应该像

public ChartInitializerBase(Func<object> retrieveData) 
{ 
      var Data = retrieveData(); //here the method GetBooks will be called and data returned
}
于 2013-03-31T22:25:09.620 回答