[英]How use C# delegate for calling different methods where each has a different out parameter?
The following question and answer addresses the use of an out parameter in a delegate: 以下问题和答案解决了在委托中使用out参数的问题:
Func<T> with out parameter 带有out参数的Func <T>
I need to take this a step further. 我需要更进一步。 I have several conversion methods (functions), where I would like to utilize a delegate. 我有几个转换方法(函数),我想利用一个委托。 For example, lets start with the below sample methods: 例如,让我们从下面的示例方法开始:
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;
}
I then declared the following delegate: 然后我宣布了以下代表:
delegate V ConvertFunc<T, U, V>(T input, out U output);
What I would like to do is something like this (pseudo code): 我想做的是这样的事情(伪代码):
if (do int conversion)
func = ConvertToInt;
else if (do boolean conversion)
func = ConvertToBool;
else ...
The compiler only lets me explicitly declare the delegate identifiers as follows: 编译器只允许我显式声明委托标识符,如下所示:
ConvertFunc<string, int, bool> func1 = ConvertToInt;
ConvertFunc<string, bool, bool> func2 = ConvertToBool;
How can I declare a single identifier, to which I can assign any of a number of methods that follow the above pattern (based on the type of conversion I wish to perform)? 如何声明单个标识符,我可以为其分配上述模式中的任何一种方法(基于我希望执行的转换类型)?
Update: 更新:
Assuming a dictionary containing string/object value pairs of: 假设包含字符串/对象值对的字典:
private Dictionary<string, object> dict = new Dictionary<string, object>();
With values, such as: 使用值,例如:
this.dict.Add("num", 1);
this.dict.Add("bool", true);
Based on the answer, I was able to implement my delegate as follows: 根据答案,我能够实现我的代理如下:
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);
}
I think you're looking for something like 我想你正在寻找类似的东西
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.