我已经想使用一个碰到类似的问题TryParse/Convert/etc.
,我的方法有时需要知道如何和为什么会失败。
我最终从一些序列化程序如何处理错误和使用事件中获得灵感。这样,我TryX(..., out T)
方法的语法看起来就和其他语法一样清晰,并且可靠地返回了false
模式所暗示的简单语法。
但是,当我需要更多详细信息时,只需添加一个事件处理程序,然后在所需的复杂或简单包中获取所需的任何结果(MyEventArgs
如下所示)。将其添加到字符串列表,添加ExceptionDispatchInfo
和捕获Exception;让呼叫者决定是否以及如何处理任何出错的地方。
public class Program
{
public static void Main()
{
var c = new MyConverter();
//here's where I'm subscibing to errors that occur
c.Error += (sender, args) => Console.WriteLine(args.Details);
c.TryCast<int>("5", out int i);
}
}
//here's our converter class
public class MyConverter
{
//invoke this event whenever something goes wrong and fill out your EventArgs with details
public event EventHandler<MyEventArgs> Error;
//intentionally stupid implementation
public bool TryCast<T>(object input, out T output)
{
bool success = true;
output = default (T);
//try-catch here because it's an easy way to demonstrate my example
try
{
output = (T)input;
}
catch (Exception ex)
{
success = false;
Error?.Invoke(this, new MyEventArgs{Details = ex.ToString()});
}
return success;
}
}
//stores whatever information you want to make available
public class MyEventArgs : EventArgs
{
public string Details {get; set;}
}
Parse()
。