带构造函数的参数传递方法

时间:2018-11-14 13:40:15

标签: c# .net delegates

我有一个Manager类DataManger.cs,其中包含一种从特定人员获取数据的方法。

public class DataManager
{
    public DataType GetDataByIdNameAge (uint id, string name, int age)
    {...}   
}

我有一个Builder类,它创建Office类:

public class Builder
{
    private DataManager _dataManager;

    public Builder()
    {
        _dataManager = new DataManager();
    }

    // Creates multiple Office objects
    public void Create()
    {
        var office = new Office();
    }
}

public class Office
{
    private Func<UInt32, UInt32, UInt32> _getDataByIdNameAge { get; }

    public Office(Func<uint, string, int> getDataByIdNameAge )
    {
        _getDataByIdNameAge = getDataByIdNameAge ;
    }

}

现在,我想将GetDataByIdNameAge方法(uint id,字符串名称,int age)传递给每个创建的Office对象,并在那里使用它。但是我现在不知道如何创建Office对象来传递方法。

2 个答案:

答案 0 :(得分:1)

只需传递不带括号的方法名即可。

public class DataManager
{
    public DataType GetDataByIdNameAge (uint id, string name, int age)
    {...}   
}


public class Builder
{
    private DataManager _dataManager;

    public Builder()
    {
        _dataManager = new DataManager();
    }

    // Creates multiple Office objects
    public void Create()
    {
        var office = new Office(_dataManager.GetDataByIdNameAge);  // <---
    }
}

public class Office
{
    // LMFTFU                        
    private Func<uint, string, int, DataType> _getDataByIdNameAge { get; }
    //                              ^^^^^^^^ don't forget the return datatype

    public Office(Func<uint, string, int, DataType> getDataByIdNameAge )
    {
        _getDataByIdNameAge = getDataByIdNameAge;
    }

}

答案 1 :(得分:1)

我倾向于将DataManager抽象到IDataManager接口,然后Office将具有一个IDataManager对象,该对象将用于任何“数据管理”,如下所示:

public class DataType
{
}

public interface IDataManager
{
    DataType GetDataByIdNameAge(uint id, string name, int age);
}

public class DataManager : IDataManager
{
    public DataType GetDataByIdNameAge(uint id, string name, int age)
    {
        return null;
    }
}

public class Builder
{
    // Creates multiple Office objects
    public void Create()
    {
        var office = new Office(new DataManager());
    }
}

public class Office
{
    private IDataManager dataManager;

    public Office(IDataManager dataManager)
    {
        this.dataManager = dataManager;
    }

    public void DoSomething()
    {
        DataType dataType = dataManager.GetDataByIdNameAge(1, "SomeName", 18);
    }
}

我认为这比传递方法的详细信息作为Func更为优雅。