我是编程新手,我正在学习C#。我正在开发一个程序来加密和解密在文本框中输入的文本。
当用户点击按钮加密或解密文本时,我想确保文本和密码文本框不为空。所以,我正在使用逻辑条件运算符&&
和!=
来评估文本框,然后运行加密文本的代码。当我将文本框的text属性的值与空字符串进行比较时,我似乎得到了错误的结果。
当我单击加密或解密按钮而文本框中没有任何数据时,语句:if (text != " " && encryptPassword != " ")
的行为就好像每个测试都为真,并且无论如何都要运行加密或解密代码。我已尝试使用equals
,使用括号,并将顺序撤销无效。请帮忙。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CryptoMakerII
{
public partial class CryptoMakerII : Form
{
public CryptoMakerII()
{
InitializeComponent();
}
private void UpdateControls(string crypto)
{
if (crypto == "Encrypt")
{
lblEncryptPassword.Visible = false;
txtEncryptPassword.Visible = false;
btnEncrypt.Visible = false;
txtDecryptPassword.Visible = true;
btnDecrypt.Visible = true;
lblDecryptPassword.Visible = true;
lblText.Text = "Encrypted Text";
//txtDecryptPassword.Text = " ";
//txtEncryptPassword.Text = " ";
}
else
{
lblEncryptPassword.Visible = true;
txtEncryptPassword.Visible = true;
btnEncrypt.Visible = true;
txtDecryptPassword.Visible = false;
btnDecrypt.Visible = false;
lblDecryptPassword.Visible = false;
lblText.Text = "Text to Encrypt";
txtDecryptPassword.Text = " ";
txtEncryptPassword.Text = " ";
}
}
private void btnEncrypt_Click(object sender, EventArgs e)
{
DES_Crypto desCrypto = new DES_Crypto();
string text = txtText.Text;
string encryptPassword = txtEncryptPassword.Text;
if (text != " " && encryptPassword != " ")
{
string encryptedText = desCrypto.EncryptString(text, encryptPassword);
txtText.Text = encryptedText;
UpdateControls("Encrypt");
}
else
{
MessageBox.Show("Please enter text to encrypt and password");
}
}
private void btnDecrypt_Click(object sender, EventArgs e)
{
DES_Crypto desCrypto = new DES_Crypto();
if (txtText.Text != " " && txtDecryptPassword.Text != " ")
if (txtDecryptPassword.Text == txtEncryptPassword.Text)
{
string decryptedText = desCrypto.DecryptString(txtText.Text, txtDecryptPassword.Text);
txtText.Text = decryptedText;
UpdateControls("Decrypt");
}
else
{
MessageBox.Show("The password is incorrect!");
}
else
MessageBox.Show("Please enter password to decrypt");
}
}
}
答案 0 :(得分:2)
您正在检查字符串是否完全等于1个空格字符,而不是检查它是否为空。 C#有一个内置方法来检查字符串是否为空:
pthread_mutex_lock
所以而不是
pthread_mutex_lock
尝试
string.IsNullOrEmpty(str)