Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/338.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 循环设置构造函数中的变量_C#_Hash_Md5 - Fatal编程技术网

C# 循环设置构造函数中的变量

C# 循环设置构造函数中的变量,c#,hash,md5,C#,Hash,Md5,我试图将变量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.Wr

我试图将变量
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();
    }
}
公共类Usuario
{
公共int ID{get;set;}
[必需]
公共字符串Nome{get;set;}
[必需]
公共字符串Senha{
获取{return Senha;}
设置{Console.WriteLine(“valor”+值);
this.Senha=CalculateMD5Hash(value);}
}
公共静态字符串CalculateMD5Hash(字符串输入){
//步骤1,从输入计算MD5散列
MD5 MD5=MD5.Create();
byte[]inputBytes=System.Text.Encoding.ASCII.GetBytes(输入);
byte[]hash=md5.ComputeHash(inputBytes);
//步骤2,将字节数组转换为十六进制字符串
StringBuilder sb=新的StringBuilder();
for(int i=0;i
但实际情况是,该类进入一个循环,并对原始散列进行散列

例如:value=123

值1=202CB962AC59075B964B07152D234B70(值的散列)

值2=D9840773233FA6B19FDE8CAF765402F5(值1的散列)


如何停止此循环并触发函数一次?

您的属性定义不正确。不仅setter在调用自身,getter也在调用自身,这将导致堆栈溢出

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

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


顺便说一句,因为您特别提到了“密码”这个词,所以除非您使用它来访问传统系统,否则您真的应该这样做。

在这种情况下,您需要使用backing字段定义属性

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

你在哪里为value1和value2赋值呢?因为现在这似乎很少见,我建议你实际使用调试器来找出a)它将进入一个循环,b)正在计算什么值。投票表决MD5的使用只是为了使用散列。我认为应用程序是如何学习的不是问题。但是对于一个大型的商业应用程序,我使用您的提示。