简体   繁体   中英

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); and execute the line, the program stops further execution and just shows me a blank 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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