【问题标题】:C# code with Dictionary to Java code with Hashtable带有字典的 C# 代码到带有 Hashtable 的 Java 代码
【发布时间】:2022-11-12 15:13:03
【问题描述】:

我是 java hashTables 的新手。我发现以下带有字典的 C# 代码。但我想要它在 Java 中,因为我不知道 C#。任何人都可以建议我这个java代码吗?

public class DatabaseStatementFactory
{
    private Dictionary<DatabaseName, IDatabaseStatement> _statementByDatabaseName
        = new Dictionary<DatabaseName, IDatabaseStatement>()
        {
                { DatabaseName.SqlServer, new SqlServerDatabaseStatement() },
                { DatabaseName.Postgres, new PostgresDatabaseStatement() },
                { DatabaseName.MySql, new MySQLDatabaseStatement() },
        };

    public IDatabaseStatement GetInstanceByType(DatabaseName databaseName) =>
        _statementByDatabaseName[databaseName];
}

我试过这个,但这告诉我一个错误。

    Hashtable<DatabaseType, DatabaseStatementService> dbTypeHashTable = 
            new Hashtable<DatabaseType, DatabaseStatementService>();
    
 
    
            SqlServerDatabaseStatementImpl sqlServerDatabaseStatementImpl = new SqlServerDatabaseStatementImpl();
            PostgresDatabaseStatementImpl postgresDatabaseStatementImpl = new PostgresDatabaseStatementImpl();
            MySQLDatabaseStatementImpl mySQLDatabaseStatementImpl = new MySQLDatabaseStatementImpl();
           
            
            dbTypeHashTable.put(DatabaseType.sqlserver,sqlServerDatabaseStatementImpl);    
            dbTypeHashTable.put(DatabaseType.postgres,postgresDatabaseStatementImpl);    
            dbTypeHashTable.put(DatabaseType.mysql,mySQLDatabaseStatementImpl);    
            

error : 语法错误,插入 "Identifier (" 来完成 MethodHeaderName

【问题讨论】:

    标签: java c# dictionary hashtable


    【解决方案1】:

    我是 java 专家,但应该是这样的。

    import java.util.*;
    
    public class DatabaseStatementFactory
    {
        private HashMap<DatabaseName, IDatabaseStatement> _statementByDatabaseName = new HashMap<DatabaseName, IDatabaseStatement>(Map.ofEntries(Map.entry(DatabaseName.SqlServer, new SqlServerDatabaseStatement()), Map.entry(DatabaseName.Postgres, new PostgresDatabaseStatement()), Map.entry(DatabaseName.MySql, new MySQLDatabaseStatement())));
    
        public final IDatabaseStatement GetInstanceByType(DatabaseName databaseName)
        {
            return _statementByDatabaseName.get(databaseName);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-17
      • 1970-01-01
      相关资源
      最近更新 更多