我有一个函数希望利用“正确”的方式来执行 .NET 4.5 中提供的操作:
public DbDataAdapater CreateDataAdapter(DbConnection connection)
{
#IFDEF (NET45)
return DbProviderFactories.GetFactory(connection).CreateDataAdapter();
#ELSE
//We can't construct an adapter directly
//So let's run around the block 3 times, before potentially crashing
DbDataAdapter adapter;
if (connection is System.Data.SqlClient.SqlConnection)
return new System.Data.SqlClient.SqlDataAdapter();
if (connection is System.Data.OleDb.OleDbConnection)
return new System.Data.OleDb.OleDbDataAdapter();
if (connection is System.Data.Odbc.OdbcConnection)
return new System.Data.Odbc.OdbcDataAdapter();
//Add more DbConnection kinds as they become invented
if (connection is SqlCeConnection)
return new SqlCeDataAdapter();
if (connection is MySqlConnection)
return new MySqlDataAdapter();
if (connection is DB2Connection)
return new DB2DataAdapter();
throw new Exception("[CreateDataAdapter] Unknown DbConnection type: " + connection.GetType().FullName);
#END
}
我能找到的唯一方法是让每个使用此共享代码来更改他们的 Visual Studio 解决方案的人。
这不会发生;它必须正常工作,否则根本不会被使用。
当解决方案针对早期版本的 .NET 框架时,有没有办法定义掉非功能性代码?
换句话说,如果编译如下,那就太好了:
public DbDataAdapter CreateDataAdapter(DbConnection conn)
{
if (System.Runtime.Version >= 45)
return DbProviderFactories.GetFactor(connection).CreateDataAdapter();
else
{
//...snip the hack...
}
}
但是如果目标框架太低,它就不会编译。