C# shortcut for #if … #else … #endif like #define

2019-03-06 12:57发布

问题:

In C# dotNET for Mono, is there an easier way of doing this?

#if __MonoCS__
    public static SqliteConnection NewConnection
#else
    public static SQLiteConnection NewConnection
#endif

In C I would be able to #if and then #define something, #else and define it as something else.

I know that the C# preprocessor doesn't allow what I want, but is there a simpler way of coping with the differences between SQLite for Windows and Linux?

Thanks,
Jim


Thanks to those who answered.
Files that depend on SQLite now contain statements like this at the beginning:

#if __MonoCS__
    using Mono.Data.Sqlite;
    using SQLiteCommand =     Mono.Data.Sqlite.SqliteCommand;
    using SQLiteConnection =  Mono.Data.Sqlite.SqliteConnection;
    using SQLiteException =   Mono.Data.Sqlite.SqliteException;
    using SQLiteParameter =   Mono.Data.Sqlite.SqliteParameter;
    using SQLiteTransaction = Mono.Data.Sqlite.SqliteTransaction;
#else
    using System.Data.SQLite;
#endif

In C I would put all that in a .h file and #include it where needed. Is there a way to do that in a Mono C# project? Nothing I tried worked.

Thanks again,
Jim

回答1:

Well, you can use a using alias directive:

#if __MonoCS__
using SQLiteConnection = Foo.Bar.SqliteConnection;
#endif

Then you can use SQLiteConnection everywhere within the same file.

You may want to use the adapter pattern to put this just in a single piece of code though, so all the rest of your code can be the same either way.