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

…衆ロ難τιáo~ 提交于 2020-02-20 08:47:10

问题


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.



来源:https://stackoverflow.com/questions/279374/how-do-i-use-net-reflection-to-search-for-a-property-by-name-ignoring-case

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!