Passing multiple methods (delegate?)

use*_*965 6 c#

I'm trying to develop a framework for several applications we are developing here and one of the framework classes I am trying to build is for creating a database. Ideally, I would have a method where I could pass it the following two methods: CreateDatabaseTables() and ResetDatabaseValues();

For instance, I might have three applications which I'll call Application1, Application2 and Application3; each one these applications would have a different database schema which I would incorporate into code (e.g. the CreateDatabaseTables has a bunch of "Create Table" commands). I want to create a single database method that can be utilized by each of these so it would look something like:

Application1

BuildLocalDatabase(CreateTablesForApp1(),ResetDatabaseValuesforApp1())
Run Code Online (Sandbox Code Playgroud)

Application2

BuildLocalDatabase(CreateTablesForApp2(),ResetDatabaseValuesforApp2())
Run Code Online (Sandbox Code Playgroud)

Application3

 BuildLocalDatabase(CreateTablesForApp3(),ResetDatabaseValuesforApp3())
Run Code Online (Sandbox Code Playgroud)

The BuildLocalDatabase method would do something like:

publid bool BuildLocalDatabase(CreateTablesForApp(),ResetDatabaseValuesforApp())
{
   - see if database file exists; if it does, delete it
   - create a new database file
   - call CreateTablesForApp
   - if the tables were created successfully, call ResetDatabaseValuesForApp
}
Run Code Online (Sandbox Code Playgroud)

Any thoughts on how I would go able doing this. There's actually a bunch of validation and other stuff that I would want to do in the BuildLocalDatabase function and obviously my goal here is to minimize the amount of duplication code in each application...any suggestions on how one might go about doing this. I think in C++, I could have just passed the CreateTablesForApp and ResetDatabaseValuesForApp methods as function points, but it doesn't seem like there is a way to do this in C#. And delegates does seem to handle it well since I'm really only limited to one method (and the multicast seems to want to run the methods twice).

Ree*_*sey 4

您将需要使用委托:

public bool BuildLocalDatabase(Func<Database, bool> createTables, Action<Database> resetValues)
{
     // Do initialization
     if (createTables(db))
     {
           resetValues(db);
     }
}
Run Code Online (Sandbox Code Playgroud)

然后您可以将其称为:

BuildLocalDatabase( (db) => CreateTablesForApp1(), (db) => ResetDatabaseValuesforApp1() );
Run Code Online (Sandbox Code Playgroud)

(我放入了一个“Database”参数,以防您需要它 - 如果您不需要,您可以只使用Func<bool>and Action,不带该参数,直接传递方法名称而不是 lambda。通常这样的方法需要某种形式的参数,例如数据库连接等,所以我将其放入。)