循环在构造函数中设置变量

Loop setting a variable in constructor

我正在尝试将变量 Senha(我的系统密码)设置为原始值的 md5 哈希值。

public class Usuario
{
        public int ID { get; set; }
        [Required]
        public string Nome { get; set; }
        [Required]
    public string Senha {
        get { return Senha; }
        set { Console.WriteLine("valor"+value );
            this.Senha = CalculateMD5Hash(value); }
    }

    public static String CalculateMD5Hash(String input) {

            // step 1, calculate MD5 hash from input
            MD5 md5 = MD5.Create();
            byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
            byte[] hash = md5.ComputeHash(inputBytes);
            // step 2, convert byte array to hex string
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < hash.Length; i++) {
                sb.Append(hash[i].ToString("X2"));
            }
            return sb.ToString();
    }
}

但是发生的事情是 class 进入一个循环并生成原始散列的散列。

例如:值 = 123

value1 = 202CB962AC59075B964B07152D234B70(哈希值)

value2 = D9840773233FA6B19FDE8CAF765402F5(value1 的哈希值)

我怎样才能停止这个循环并只触发一次函数?

您的 属性 定义不正确。不仅你的 setter 正在调用自己,你的 getter 也在调用自己并且会导致堆栈溢出。

相反,您需要提供一个 支持字段 来存储 属性:

的值
private string _senha;
public string Senha 
{
    get { return _senha; }
    set 
    { 
        Console.WriteLine("valor"+value );
        _senha = CalculateMD5Hash(value);
    }
}

对了,既然你特地提到了'password'这个词,using MD5 for passwords is a bad idea, so unless you're using this to access a legacy system you should really do it the right way

在这种情况下,您需要定义 属性 with backing field。

private string _senha;
public string Senha 
{
    get { return _senha; }
    set { Console.WriteLine("valor"+value );
          _senha = CalculateMD5Hash(value); 
        }
}