以下问题和答案解决了在委托中使用out参数的问题:
我需要更进一步。我有几个转换方法(函数),我想利用一个委托。例如,让我们从下面的示例方法开始:
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;
}
然后我宣布了以下代表:
delegate V ConvertFunc<T, U, V>(T input, out U output);
我想做的是这样的事情(伪代码):
if (do int conversion)
func = ConvertToInt;
else if (do boolean conversion)
func = ConvertToBool;
else ...
编译器只允许我显式声明委托标识符,如下所示:
ConvertFunc<string, int, bool> func1 = ConvertToInt;
ConvertFunc<string, bool, bool> func2 = ConvertToBool;
如何声明单个标识符,我可以根据上述模式分配任何多种方法(基于我希望执行的转换类型)?
更新
假设包含字符串/对象值对的字典:
private Dictionary<string, object> dict = new Dictionary<string, object>();
使用值,例如:
this.dict.Add("num", 1);
this.dict.Add("bool", true);
根据答案,我能够按如下方式实施我的代表:
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);
}
答案 0 :(得分: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;
}