2

这是一些示例代码。我收到错误“无法将类型'string'隐式转换为'T'”

public ValueTuple<string, T> TestMethod<T>()
{
    return ("test", "");
}

我该怎么做呢?这超出了 ValueTuple 的限制吗?

我正在使用的真实代码示例

public ValueTuple<bool, T> RunSelectAllCommand<T>(MySqlCommand command, 
    List<MySqlParameter> parameterCollection) where T : class
{
    using (MySqlConnection conn = new MySqlConnection(connectionString))
    using (var cmd = conn.CreateCommand())
    {
        conn.Open();            
        cmd.CommandText = command.CommandText;

        // if parameters for query are specified, add them here.
        if (parameterCollection != null)
        {
            cmd.Parameters.AddRange(parameterCollection.ToArray());
        }
        using (var reader = cmd.ExecuteReader())
        {
            // We're selecting all keys from registration database 
            // this is probably a horrible design. oh, well...
            if (typeof(T) == typeof(KeyRow))
            {
                List<KeyRow> data = new List<KeyRow>();
                while (reader.Read())
                {
                    data.Add(new KeyRow(reader["keycode"].ToString(), 
                        reader["apikey"].ToString(), 
                        reader["ipaddress"].ToString(),
                        DateTime.Parse(reader["date"].ToString()), 
                        reader["hwid"].ToString() ?? ""));
                }

                return (true, data as T);
            }
        }
    }

    return (false, null);
}
4

1 回答 1

1

使用您的示例,我将以下内容作为示例来说明如何做您想做的事情。这使用通用实现方法来重用您可能返回的各种类型,这是一种非通用方法来公开返回这些类型。

public ValueTuple<bool, List<KeyRow>> RunSelectAllKeyRowCommand(IDbCommand command, List<IDataParameter> parameterCollection) =>
    RunSelectAllCommandImpl<KeyRow>(command, 
                                    parameterCollection,
                                    reader => new KeyRow(reader["keycode"].ToString(), reader["apikey"].ToString(), reader["ipaddress"].ToString(), DateTime.Parse(reader["date"].ToString()), reader["hwid"].ToString() ?? ""));

private ValueTuple<bool, List<T>> RunSelectAllCommandImpl<T>(IDbCommand command, List<IDataParameter> parameterCollection, Func<IDataReader, T> mapper) where T : class
{
    using (IDbConnection conn = GetDataConnection())
    using (var cmd = conn.CreateCommand())
    {
        conn.Open();
        cmd.CommandText = command.CommandText;

        foreach(var parameter in parameterCollection) // if parameters for query are specified, add them here.
            cmd.Parameters.Add(parameter);

        using (var reader = cmd.ExecuteReader())
        {
            List<T> data = new List<T>();

            while (reader.Read())
                data.Add(mapper(reader));

            return (true, data);
        }
    }

    return (false, null);
}
于 2018-04-20T22:03:16.407 回答