C# 字典存储操作/方法

Joh*_*ohn 2 c# dictionary

我有一本带string键的字典,例如123456789。现在,在我的应用程序内的某个其他点,我希望我的字典查找此键,然后运行该方法本身(沿着键存储)或以某种方式返回该函数,以便我可以手动添加参数。这可能吗?

Bob*_*ale 6

您需要创建一个dictionary<string, Action>,这将是没有参数的。

例如

static class MyActions {
  static Dictionary<string,Action> wibble = new Dictionary<string,Action>();
}
Run Code Online (Sandbox Code Playgroud)

我使用了静态,如果您可以传递引用/检索引用,则没有必要。

然后添加动作...

MyActions.wibble["123456789"] = () => { // do action };
Run Code Online (Sandbox Code Playgroud)

或引用无参数方法

MyActions.wibble["123456789"] = () => MyMethod;
Run Code Online (Sandbox Code Playgroud)

然后调用它;

MyActions.wibble["123456789"]()
Run Code Online (Sandbox Code Playgroud)

假设密钥存在,您可以使用 try get 甚至MyActions.wibble["123456789"]?.Invoke()

如果需要参数,根据参数的数量制作类型Action<T>等的字典。Action<T1, T2>

例如wibble = new Dictionary<string,Action<int>>()

进而wibble["123456789"] = x => {action with x}

wibble["123456789"](42)


Man*_*mer 5

听起来像是一个简单的任务。(不包括健全性检查)

Dictionary<string,Action<object>> dict;

public Action<object> GetFunction(string key)
{
    return dict[key];
}

public void CallFunction(string key, object parameter)
{
    dict[key](parameter);
}
Run Code Online (Sandbox Code Playgroud)