简体   繁体   English

使用反射获取可空布尔值

[英]Getting the value of a Nullable Boolean using Reflection

I'm trying to the value of a nullable boolean using reflection. 我正在尝试使用反射来获取可为空的布尔值。 The values are coming from a DB so I have to keep them the same. 这些值来自数据库,因此我必须保持相同。

Here is the code I am using. 这是我正在使用的代码。

public partial class PrinterConfigUC : UserControl
{
    prtsetup Printer { get; set; }

    public PrinterConfigUC(prtsetup printer)
    {
        InitializeComponent();
        this.Printer = printer;
        lblPrinterName.Text = Printer.prtname;

        var properties = printer.GetType().GetProperties();          

        foreach (var prop in properties)
        {
            //In debug, a nullable bool had a type name of "Nullable`1"
            if (prop.PropertyType.Name.Equals("Nullable`1"))
            {
                bool? tempBool = (bool?)prop.GetValue(prop, null);
            }
        }
    }

If I put a break point at bool? tempBool = (bool?)prop.GetValue(prop, null); 如果我在bool? tempBool = (bool?)prop.GetValue(prop, null);设置一个断点bool? tempBool = (bool?)prop.GetValue(prop, null); bool? tempBool = (bool?)prop.GetValue(prop, null); and execute the line, the program stops further execution and just shows me a blank winform. 并执行该行,程序停止进一步执行,只显示一个空白的winform。 Nothing else happens. 什么都没发生。 There are no error messages and the program doesn't crash, it just hangs on that one line. 没有错误消息,程序也不会崩溃,它只是挂在那一行上。

Change this: 更改此:

bool? tempBool = (bool?)prop.GetValue(prop, null);

To: 至:

bool? tempBool = (bool?)prop.GetValue(printer, null);

The first arg of GetValue is the source, which is the printer in your example above, not the property, which is metadata. GetValue的第一个参数是源,即上面示例中的打印机,而不是属性(即元数据)。

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

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