C# BindingFlags.IgnoreCase 不适用于 Type.GetProperty()?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/264745/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 20:27:29  来源:igfitidea点击:

BindingFlags.IgnoreCase not working for Type.GetProperty()?

c#reflectiongetpropertybindingflags

提问by Boris Callens

Imagine the following

想象以下

A type T has a field Company. When executing the following method it works perfectly:

类型 T 有一个字段 Company。执行以下方法时,它完美地工作:

Type t = typeof(T);
t.GetProperty("Company")

Whith the following call I get null though

虽然下面的电话我得到了空值

Type t = typeof(T);
t.GetProperty("company", BindingFlags.IgnoreCase)

Anybody got an idea?

有人有想法吗?

采纳答案by Pop Catalin

You've overwritten the default look-up flags, if you specify new flags you need to provide all the info so that the property can be found. For example: BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance

您已经覆盖了默认查找标志,如果您指定新标志,您需要提供所有信息以便可以找到该属性。例如:BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance

回答by leppie

You need to add BindingFlags.Public | BindingFlags.Instance

你需要添加 BindingFlags.Public | BindingFlags.Instance

回答by Josh Warner-Burke

Thanks, this really helped me out in a pinch today. I had audit information saved, but with incorrect casing on the property names. (The auditing is built into a datalayer.) Anyway so I had to add IgnoreCase as a binding flag, but then it still didn't work, till my coworker found this answer. The resulting function:

谢谢,这真的帮助了我今天的紧要关头。我保存了审计信息,但属性名称的大小写不正确。(审计内置在数据层中。)无论如何,我不得不添加 IgnoreCase 作为绑定标志,但它仍然不起作用,直到我的同事找到了这个答案。结果函数:

public static void SetProperty(Object R, string propertyName, object value)
{
    Type type = R.GetType();
    object result;
    result = type.InvokeMember(
        propertyName, 
        BindingFlags.SetProperty | 
        BindingFlags.IgnoreCase | 
        BindingFlags.Public | 
        BindingFlags.Instance, 
        null, 
        R, 
        new object[] { value });
}

This is part of a class I call DotMagic.

这是我称之为 DotMagic 的课程的一部分。