简体   繁体   中英

C# debug - looking for a certain value without knowing which property has it

My question is this: If I know that a property of the object has value "example", how can I find which property it is, without checking every possible property of the object when I debug?

I think I'm a bit unclear. For example, I have an object of ImagePart. When I debug, I want to see the value of TargetName. To do that, I should go withe the mouse over the object, then over Non-Public members. But, if the value I wanna see is much deeper, I have trouble finding it.

If I understood correctly, you have an object with a lot of properties, then you can make a method in that class that would 'scan' all the properties using C# reflection.

Create a method like this in the class of the object you want to analyze:

    string PropertyThatHasCertainValue(object Value)
    {
        Type myType = this.GetType();

        while(myType != typeof(object))
        {
            foreach (PropertyInfo property_info in myType.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
            {
                if (object.Equals(property_info.GetValue(this, null), Value))
                {
                    return property_info.Name;
                }
            }
            myType = myType.BaseType;
        }
        return "No property has this value";
    }

Then in the watch, add a following watch:

MyObjectInstance.PropertyThatHasCertainValue(ValueYouAreLookingFor)

Note that you might want to use something else but object as a parameter, to make it easier to type in the watch, but VS watch Window you can easily type not only numbers and strings but also enums. Visual Studio watches are extremely powerful, they will almost always evaluate the expression correctly.

I have added the while loop to go recursively through all the parents. BindingFlags.NonPublic will return all private and protected methods of the class, but not the private methods of base classes. Navigating through all the base classes, until hitting Object will solve this.

With VS 2010, you can pin-UP the property. So next time, when you hit the debug point, the corresponding value will be automatically highlighted. For more : http://weblogs.asp.net/pawanmishra/archive/2009/12/26/another-vs-2010-feature-pin-up.aspx

A similar question has been asked here . Please see my answer there: the Search feature I was talking about works for property values just as it does for property names.

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