Pregunta

Esta función se llama desde form_onload. Básicamente estoy leyendo el registro, determinando qué casillas están marcadas y luego reflejando eso en la GUI.

¿Hay alguna forma de condensar esto y escribir un código mejor? ¿Qué tal usar la propiedad CheckState?

Gracias.

Woody

private void checkExcelSettings()
    {
        // Read what the values are for the checkboxes first and assign them to a string.
        string _excelEnable = Convert.ToString(Registry.GetValue(@"HKEY_CURRENT_USER\Software\Mask Data\", "ExcelEnableHash", "Unchecked"));
        string _excelSSN = Convert.ToString(Registry.GetValue(@"HKEY_CURRENT_USER\Software\Mask Data\", "ExcelSSNHash", "Unchecked"));
        string _excelCC = Convert.ToString(Registry.GetValue(@"HKEY_CURRENT_USER\Software\Mask Data\", "ExcelCCHash", "Unchecked"));
        string _excelWells = Convert.ToString(Registry.GetValue(@"HKEY_CURRENT_USER\Software\Mask Data\", "ExcelWellsHash", "Unchecked"));
        string s=@"t\""; //unimportant no-op to placate stackoverflow syntax highlighter.


        // Now let's make sure we reflect what they are supposed to be in the GUI.
        if (_excelEnable == "Checked")
        {
            chkbxExcelEnable.Checked = true;
        }
        else
        {
            chkbxExcelEnable.Checked = false;
        }

        if (_excelSSN == "Checked")
        {
            chkbxExcelSSN.Checked = true;
        }
        else
        {
            chkbxExcelSSN.Checked = false;
        }

        if (_excelCC == "Checked")
        {
            chkbxExcelCC.Checked = true;
        }
        else
        {
            chkbxExcelCC.Checked = false;
        }

        if (_excelWells == "Checked")
        {
            chkbxExcelWellsFargo.Checked = true;
        }
        else
        {
            chkbxExcelWellsFargo.Checked = false;
        }
    }
¿Fue útil?

Solución

Bueno, al menos podrías reducirlo a:

chkbxExcelCC.Checked = _excelCC.Equals("Checked");

De esta manera evita todas las declaraciones if / else.

Otros consejos

Puede eliminar todas las condiciones innecesarias si / de lo contrario colocando la condición en línea con la asignación. También puede hacer que la ruta de la clave principal sea una constante. Sin embargo, para simplificarlo realmente, puede tomar la lógica repetida de buscar una clave y compararla con "Comprobado". y ponerlo en un método separado:

private void checkExcelSettings()
{
    // Now let's make sure we reflect what they are supposed to be in the GUI.
    chkbxExcelEnable.Checked = IsChecked("ExcelEnableHash");
    chkbxExcelSSN.Checked = IsChecked("ExcelSSNHash");
    chkbxExcelCC.Checked = IsChecked("ExcelCCHash");
    chkbxExcelWellsFargo.Checked = IsChecked("ExcelWellsHash");
}

private static bool IsChecked(string regValue)
{
    return Convert.ToString(
               Registry.GetValue(
                   @"HKEY_CURRENT_USER\Software\Mask Data\",
                   regValue,
                   "Unchecked")) == "Checked";
}
private void checkExcelSettings()
{
    // Read what the values are for the checkboxes first and assign them to a string.
    string _excelEnable = Convert.ToString(Registry.GetValue(@"HKEY_CURRENT_USER\Software\Mask Data\", "ExcelEnableHash", "Unchecked"));
    string _excelSSN = Convert.ToString(Registry.GetValue(@"HKEY_CURRENT_USER\Software\Mask Data\", "ExcelSSNHash", "Unchecked"));
    string _excelCC = Convert.ToString(Registry.GetValue(@"HKEY_CURRENT_USER\Software\Mask Data\", "ExcelCCHash", "Unchecked"));
    string _excelWells = Convert.ToString(Registry.GetValue(@"HKEY_CURRENT_USER\Software\Mask Data\", "ExcelWellsHash", "Unchecked"));

    // Now let's make sure we reflect what they are supposed to be in the GUI.
    chkbxExcelEnable.Checked = (_excelEnable == "Checked");
    chkbxExcelSSN.Checked = (_excelSSN == "Checked");
    chkbxExcelCC.Checked = (_excelCC == "Checked");
    chkbxExcelWellsFargo.Checked = (_excelWells == "Checked");
}

Puede colocar todas sus casillas de verificación en un panel y establecer la propiedad Etiqueta de cada casilla de verificación en la clave correspondiente en el registro. Entonces podría usar este código en el evento Load del formulario:

foreach (CheckBox cb in panel1.Controls)
{
    cb.Checked = ((string)Registry.GetValue(RegPath, 
        (string)cb.Tag, "Unchecked") == "Checked");
}

Esto tiene la desventaja de no ser inmediatamente obvio para un futuro programador de mantenimiento, por lo que agregaría un comentario detallado aquí dirigido a su eventual reemplazo.

También puede prescindir de la etiqueta y simplemente nombrar cada casilla de verificación con la clave correspondiente, y luego usar " nombre cb " en lugar de " (string) cb.Tag " ;. A nadie le gusta la notación húngara, de todos modos.

private void checkExcelSettings()
    {
        string key = @"HKEY_CURRENT_USER\Software\Mask Data\";

        // Read what the values are for the checkboxes first and assign them to a string.
        string _excelEnable = Convert.ToString(Registry.GetValue(key, "ExcelEnableHash", "Unchecked"));
        string _excelSSN = Convert.ToString(Registry.GetValue(key, "ExcelSSNHash", "Unchecked"));
        string _excelCC = Convert.ToString(Registry.GetValue(key, "ExcelCCHash", "Unchecked"));
        string _excelWells = Convert.ToString(Registry.GetValue(key, "ExcelWellsHash", "Unchecked"));
        string s=@"t\""; //unimportant no-op to placate stackoverflow syntax highlighter.

        // Now let's make sure we reflect what they are supposed to be in the GUI.
        chkbxExcelEnable.Checked = (_excelEnable == "Checked");
        chkbxExcelSSN.Checked = (_excelSSN == "Checked");
        chkbxExcelCC.Checked = (_excelCC == "Checked");
        chkbxExcelWellsFargo.Checked = (_excelWells == "Checked");
    }

Use notación de mano corta para si más

chkbxExcelEnable.Checked = _excelEnable == "Checked" ? true: false;
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top