2012-07-23 52 views
2

我有課!c#如何從類返回值?

class Reg_v_no_string 
{ 
    public static string key_place = ""; 
    public static string key = ""; 
    public static string value = ""; 
    public string reg_value(string key_place, string key) 
    { 
     string value = string.Empty; 

      RegistryKey klase = Registry.CurrentUser; 
      klase = klase.OpenSubKey(key_place); 
      value = klase.GetValue(key).ToString(); 
      klase.Close(); 

     return value; 
    } 
} 

並返回空白消息框。 如何解決這個問題! 謝謝!

我怎麼能從這個類返回值?

我tryed

private void kryptonButton1_Click(object sender, EventArgs e) 
    { 
     Reg_v_no_string.key_place = @"Control Panel\Desktop"; 
     Reg_v_no_string.key_place = "WheelScrollLines"; 
     MessageBox.Show(Reg_v_no_string.value); 

    } 
+2

你應該永遠不會捕獲NullReferenceException。修正錯誤而不是捕捉異常。 – 2012-07-23 22:52:04

回答

3

您需要實際調用的方法:

private void kryptonButton1_Click(object sender, EventArgs e) 
{ 
    var value = reg_value(@"Control Panel\Desktop", "WheelScrollLines"); 
    MessageBox.Show(value); 
} 

還要考慮一些更改類:

public static class Reg_v_no_string 
{ 
    public static string reg_value(string key_place, string key) 
    { 
     string value = string.Empty; 

     RegistryKey klase = Registry.CurrentUser; 
     // todo: add some error checking to make sure the key is opened, etc. 
     klase = klase.OpenSubKey(key_place); 
     value = klase.GetValue(key).ToString(); 
     klase.Close(); 

     return value; 
    } 
} 

然後當你調用這個static類是這樣的:

// you don't need to `new` this class if it is static: 
var value = Reg_v_no_string.reg_value(@"Control Panel\Desktop", "WheelScrollLines"); 

或者,爲了保持它不是靜態的:

public class Reg_v_no_string 
{ 
    public string reg_value(string key_place, string key) 
    { 
     string value = string.Empty; 

     RegistryKey klase = Registry.CurrentUser; 
     // todo: add some error checking to make sure the key is opened, etc. 
     klase = klase.OpenSubKey(key_place); 
     value = klase.GetValue(key).ToString(); 
     klase.Close(); 

     return value; 
    } 
} 

然後調用它像這樣:

Reg_v_no_string obj = new Reg_v_no_string(); 
var value = reg_value(@"Control Panel\Desktop", "WheelScrollLines"); 
4

沒有代碼調用reg_value

因爲您正在獲取value字段的默認值(也在實例之間共享)值。

0

Reg_v_no_string.value尚未設定。
您必須致電reg_value(string key_place, string key)函數返回值。