简体   繁体   中英

C# how to get parent class property from child class

Maybe I'm a little dumb, but I need to take the value of the base class parameter from the child class. How can I do that?

My code:

using (OracleConnection connection = new OracleConnection(ConnStr)) {
  connection.Open();
  using (OracleCommand cmd = connection.CreateCommand()) {
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.CommandText = "Package.StoredProcedure";

    cmd.Parameters.Add(DbParam("in_id", OracleDbType.Int32, id));
    cmd.Parameters.Add(DbOutParam("out_success", OracleDbType.Int32, 1));

    cmd.ExecuteNonQuery();
    int out_success = cmd.Parameters.GetIntValue("out_success");
    connection.Close();
  }
}

And I wrote extension GetIntValue for OracleParameterCollection

private static int GetIntValue(this OracleParameterCollection parameter, string parameterName) {
  bool success = int.TryParse(parameter[parameterName].Value.ToString(), out int response);
  if (success == false) {
    Console.Out.WriteLine($"TryParse parameter: {parameterName}");
    throw new Exception("Unhandled Exception");
  }
  return response;
}

And I need to get in extension GetIntValue property cmd.CommandText for printing in Console - How it possible?

If you need to reference the command, let the extension method accept the command instance, instead of parameters:

private static int GetIntValue(this OracleCommand command, string paramName)
{
    var parameters = command.Parameters;

    if (!parameters.Contains(parameterName))
        throw new ArgumentException(
            $"{command.CommandText} does not contain param {parameterName}");

    if (!int.TryParse(parameters[paramName].Value.ToString(), out int response))
        throw new FormatException(
            $"could not parse {paramName} in {command.CommandText}");

    return response;
}

Note that dumping command texts on exceptions might be a bad idea from a security standpoint.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM