简体   繁体   中英

How can I make a method that takes more than one Enum type instead of me having to Cast all the time

I have these method calls and more and this method:

    App.DB.UpdateSetting("TimeInterval", (int)Time.UserInput );
    App.DB.UpdateSetting("ThemeColor", (int)Theme.Light );

    public void UpdateSetting(string setting, int value, string text="" )
    {
        lock (locker)
        {
            db2.Execute("UPDATE Setting SET Value = ?, Text = ?" +
                          " WHERE SettingType = ?", value, text, setting);
        }
    }

What I would like to do is to be able to avoid typing all those settings to (int). Is there some way I could do that?

You can use Enum instead of int . That allows you to pass any enum value you ike. The only change you need to make then is to convert the enum to an int inside your method:

public void UpdateSetting(string setting, Enum value, string text = "")
{
    var intValue = Convert.ToInt32(value);

    lock (locker)
    {
        db2.Execute("UPDATE Setting SET Value = ?, Text = ?" +
                      " WHERE SettingType = ?", intValue, text, setting);
    }
}

Now you can call it like this:

App.DB.UpdateSetting("TimeInterval", Time.UserInput );
App.DB.UpdateSetting("ThemeColor", Theme.Light );

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