0

我有一些使用 PropertyDescriptor 设置值的代码。问题是当它失败时,异常不包含信息或调用堆栈,其中包含引发异常的执行代码?在这种情况下,SetNameInternal()。该异常仅具有直到调用 SetValue 为止的信息。没有内在的例外。有什么方法可以获取这些信息以便记录?(例如在调试器之外运行应用程序时)

以下代码演示了该问题。Exception.ToString() 返回的字符串仅包含:

System.Exception:啊!在 System.ComponentModel.ReflectPropertyDescriptor.SetValue(Object component, Object value) at ConsoleApp54.Program.Main(String[] args) ... ConsoleApp54.exe' 已退出,代码为 0 (0x0)。

然而问题出在 SetNameInternal() 中。当然,在这个简单的例子中,很明显哪里出了问题,但现实世界的案例会发生更多事情,所以调用堆栈很有用。

    public class Test
{
    public string Name
    {
        get { return m_name; }
        set
        {
            m_name = value;
            SetNameInternal();
        }
    }

    void SetNameInternal()
    {
        throw new Exception("Ah!");
    }

    private string m_name;
}

class Program
{
    static void Main(string[] args)
    {
        var t = new Test();
        try
        {
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(t);
            var desc = properties.Find("Name", false);
            desc.SetValue(t, "Fail");
            //but this would return different StackTrace
            //t.Name = "Fail";
        }
        catch (Exception e)
        {
            Debug.Write(e.ToString());
        }
    }
}

小提琴

4

0 回答 0