简体   繁体   中英

c# how can return value from class?

I have class !

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;
    }
}

and this returns blank message box. How can solve this problem !? Thanks !

how can i return value from this class ?

I 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);

    }

There is no code that calls reg_value .

As result you are getting default (also shared between instances) value of value field.

You need to actually call the method:

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

Also consider some changes to your class:

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; 
    } 
} 

And then when you call this static class it is like this:

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

Or, to keep it so that it is not static:

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; 
    } 
} 

Then call it like this:

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

Reg_v_no_string.value is not set yet.
You have to call reg_value(string key_place, string key) function that will return the value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM