How do I use .Net reflection to search for a prope

2020-07-16 12:05发布

问题:

I had the following line snippet of code that searches for a propery of an instance by name:

var prop = Backend.GetType().GetProperty(fieldName);

Now I want to ignore the case of fieldName, so I tried the following:

var prop = Backend.GetType().GetProperty(fieldName, BindingFlags.IgnoreCase);

... No dice. Now prop won't find field names that have the exact case.

Hence..... How do I use .Net reflection to search for a property by name ignoring case?

回答1:

You need to specify BindingFlags.Public | BindingFlags.Instance as well:

using System;
using System.Reflection;

public class Test
{
    private int foo;

    public int Foo { get { return foo; } }

    static void Main()
    {
        var prop = typeof(Test).GetProperty("foo",
                                            BindingFlags.Public
                                            | BindingFlags.Instance 
                                            | BindingFlags.IgnoreCase);
        Console.WriteLine(prop);
    }
}

(When you don't specify any flags, public, instance and static are provided by default. If you're specifying it explicitly I suggest you only specify one of instance or static, if you know what you need.)



回答2:

Try adding the scope BindingFlags like so:

var prop = Backend.GetType().GetProperty(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase);

This works for me.