如何使用C#delegate调用不同的方法,其中每个方法都有不同的out参数?

Ela*_*lan 4 c# generics delegates func

以下问题和答案解决了在委托中使用out参数的问题:

带有out参数的Func <T>

我需要更进一步.我有几个转换方法(函数),我想利用一个委托.例如,让我们从下面的示例方法开始:

private bool ConvertToInt(string s, out int value)
{
    try
    {
        value = Int32.Parse(s);
        return true;
    }
    catch (Exception ex)
    {
        // log error
        value = 0;
    }

    return false;
}


private bool ConvertToBool(string s, out bool value)
{
    try
    {
        value = Convert.ToBoolean(s);
        return true;
    }
    catch (Exception ex)
    {
        // log error
        value = false;
    }

    return false;
}
Run Code Online (Sandbox Code Playgroud)

然后我宣布了以下代表:

delegate V ConvertFunc<T, U, V>(T input, out U output);
Run Code Online (Sandbox Code Playgroud)

我想做的是这样的事情(伪代码):

if (do int conversion)
    func = ConvertToInt;
else if (do boolean conversion)
    func = ConvertToBool;
else ...
Run Code Online (Sandbox Code Playgroud)

编译器只允许我显式声明委托标识符,如下所示:

ConvertFunc<string, int,  bool> func1 = ConvertToInt;
ConvertFunc<string, bool, bool> func2 = ConvertToBool;
Run Code Online (Sandbox Code Playgroud)

如何声明单个标识符,我可以为其分配上述模式中的任何一种方法(基于我希望执行的转换类型)?

更新:

假设包含字符串/对象值对的字典:

private Dictionary<string, object> dict = new Dictionary<string, object>();
Run Code Online (Sandbox Code Playgroud)

使用值,例如:

this.dict.Add("num", 1);
this.dict.Add("bool", true);
Run Code Online (Sandbox Code Playgroud)

根据答案,我能够实现我的代理如下:

public T GetProperty<T>(string key)
{
    ConvertFunc<string, T, bool> func = ConvertToT<T>;
    object val = this.dict[key];
    T result;
    if (func(key, out result))
        return result;
    else
        return default(T);
}
Run Code Online (Sandbox Code Playgroud)

Ron*_*ijm 6

我想你正在寻找类似的东西

private bool ConvertToT<T>(string s, out T value)
{
    try
    {
        value = (T)Convert.ChangeType(s, typeof(T));

        return true;
    }
    catch (Exception ex)
    {
        // log error // not sure what you're trying here?
        value = default(T);
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)