How can I change a bool to a 0 or a 1, can I cast it?

时间:2019-04-08 12:51:48

标签: c#

I have this method:

public void UpdatePhrase(PHRASE phraseColumn, bool value, string phraseId) 
{
   sql = string.Format("UPDATE Phrase SET " + phraseColumn.Text() + " = {0} WHERE PhraseId = '{1}'", value, phraseId);
        App.DB.RunExecute(sql);
}

It's not working correctly as it seems like I need the value of {0} needs to be a 0 or a 1.

Is there a simple way that I can take value and change it to be a 0 or a 1?

7 个答案:

答案 0 :(得分:11)

Just do value ? 1 : 0, it's that easy!

答案 1 :(得分:9)

@Sean has given to you the natural fix to your problem, but, in my view, what you really need to do here is to refactor your App.Db.RunExecute to receive parameters, so you can write

public void UpdatePhrase(PHRASE phraseColumn, bool value, string phraseId) 
{
   sql = "UPDATE Phrase SET " + phraseColumn.Text() + " = @v WHERE PhraseId = @id";
   List<SqlParameter> prms = new List<SqlParameter>
   {
      new SqlParameter {ParameterName = "@v", SqlDbType = SqlDbType.Boolean, Value = value},
      new SqlParameter {ParameterName = "@id", SqlDbType = SqlDbType.NVarChar, Value = phraseId}
   };
   App.DB.RunExecute(sql, prms);
}

This will partially remove the Sql Injection problem (I say partially because that phraseColumn.Text() is still source of concerns if its value comes from the user input)

Now RunExecute should change to

void RunExecute(string sqlCommand, List<SqlParameter> prms = null)
{
     // usual code to open connection and create a command
     ......

     // If the caller passes a parameters list, add them to the command
     if(prms != null)
        cmd.Parameters.AddRange(prms.ToArray());

     // Now execute the command
     cmd.ExecuteNonQuery();
}

The change to RunExecute uses an optional argument, so your current code is not affected by the presence of the new argument but you will be able to write better Sql code from now on.

答案 2 :(得分:0)

value ? 1 : 0

as in @Sean answer or

Convert.ToInt32(value)

ToInt32(Boolean) Converts the specified Boolean value to the equivalent 32-bit signed integer.

答案 3 :(得分:0)

您可以使用int count = updateCommand.ExecuteNonQuery;,所以if count>0,表示我们的任务是1(正确),否则0(错误)

updateCommand.Parameters.AddWithValue("@Var" , "Johne");

    try
    {
        connection.Open();
        int count = updateCommand.ExecuteNonQuery;
        if (count > 0)
            return true;
        else
            return false;
    }
    catch (SqlException ex)
    {
        throw ex;
    }
    finally
    {
        connection.Close();
    }
}

我希望你明白了^ _ ^。

答案 4 :(得分:0)

您可以做到(布尔值上的GetHashCode返回常数1/0,不计算):

true.GetHashCode() // 1
false.GetHashCode() // 0

答案 5 :(得分:-1)

public void UpdatePhrase(PHRASE phraseColumn, bool value, string phraseId) 
{
   sql = string.Format("UPDATE Phrase SET {phraseColumn} = {value ? 1 : 0} WHERE PhraseId = '{phraseId}'");
        App.DB.RunExecute(sql);
}

But that can be subject to SQL injection attacks, so better to write it as a parameterised query.

答案 6 :(得分:-2)

For scenarios needing extreme performance, you can use the System.­Runtime.­CompilerServices.­Unsafe package to perform this conversion directly inline. This will result in native code that contains no branching or function calls.

using System.Runtime.CompilerServices;

/// ...

bool _bool;
byte _byte;

_bool = true;
_byte = Unsafe.As<bool, byte>(ref _bool);
Console.WriteLine(_byte);           //  -->  1

_bool = false;
_byte = Unsafe.As<bool, byte>(ref _bool);
Console.WriteLine(_byte);           //  -->  0

You can also use this method to set up a ref local byte variable which existentially represents the instantaneous identity of the Boolean, but viewed as a byte. This might be useful for persistently monitoring a changing { false, true } using a { 0, 1 } interpretation.

class Program
{
    static bool _bool;

    static void Main()
    {
        Task.Factory.StartNew(() => { while (true) _bool = !_bool; });

        // define a "ref local" that persistently views Boolean value '_bool' as a byte
        ref byte _byte = ref Unsafe.As<bool, byte>(ref _bool);

        while (true)
            Console.Write(_byte + " ");
    }
};

If you're unfamiliar with ref, with this technique just shown there is no "machinery" involved in any sort of "updating" or "conversion" whenever the value changes, because the ref byte is actually just a different "view" of the original Boolean entity itself.

The output is somewhat mesmerizing.

enter image description here