简体   繁体   English

如何使用反射获取属性?

[英]How to get a property using reflection?

I need to remove any reference to System.Data.SqlClient from my project.我需要从我的项目中删除对System.Data.SqlClient的任何引用。 The only instance I use it is to get a list of errors, for example:我使用它的唯一实例是获取错误列表,例如:

if (ex is SqlException)
{
    var spx = ex as SqlException;
    if (spx.Errors != null)
    {
        for (int i = 0; i < spx.Errors.Count; i++)
        { 
            var sqlError = spx.Errors[i];
        }
    }
}

Is the only alternative to use Reflection and call GetProperty as in:是使用Reflection并调用GetProperty的唯一替代方法,如下所示:

if (ex.GetType().Name == "SqlException")
{
    var errors = ex.GetType().GetProperty("Errors");
    if (errors != null)
    {}
}

This is definitely a question of Exception handling.这绝对是异常处理的问题。 First, there is one list of classifications and one set of good guidelines .首先,有一份分类清单和一套好的指导方针 Those two helped me and I consider them "required reading" on the thematic.这两个人帮助了我,我认为他们是主题上的“必读”。

A lot of the stuff you are doing there looks pretty critical.你在那里做的很多事情看起来都很关键。 You catch way to wide.你追得上宽。 Then filter by type using is.然后使用 is 按类型过滤。 But you never throw the wrong exceptions on.但是你永远不会抛出错误的异常。

Your main worry seems to be code calling your code having to deal with SqlException , as adding teh Reference is for some reason not useable.您的主要担心似乎是代码调用您的代码必须处理SqlException ,因为添加参考由于某种原因不可用。 Usually the solution is to make your own Exception Class and put the Sql one into inner Exception.通常解决方案是制作自己的异常 Class 并将 Sql 放入内部异常中。 The guidelines above have all the details I could give you on that.上面的指南包含了我可以给你的所有细节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM