C# : propertyinfo always empty

标签 c# reflection

我对 C# 反射有疑问。 我想要反射(reflect)的对象如下:

public partial class ApplicationUser : IdentityUser
{
    public ApplicationUser()
    {
    }

    public decimal CustomerId { get; set; }

    public string AlexaAccessToken { get; set; }

    public string GoogleHomeAccessToken { get; set; }
}

我用来反射(reflect)的代码如下:

    Dictionary<string,string> GetReplacement(ApplicationUser applicationUser)
    { 

        Dictionary<string, string> toRet = new Dictionary<string, string>();

        PropertyInfo[] propertyInfos;
        propertyInfos = typeof(ApplicationUser).GetProperties(BindingFlags.Public);

        Array.Sort(propertyInfos,
            delegate (PropertyInfo propertyInfo1, PropertyInfo propertyInfo2)
                { return propertyInfo1.Name.CompareTo(propertyInfo2.Name); });


        foreach (PropertyInfo propertyInfo in propertyInfos)
        {
            toRet.Add(propertyInfo.Name,propertyInfo.GetValue(applicationUser).ToString());
        }

        return toRet;
    }

问题是字典总是空的,因为 propertyinfo 总是空的。 问题是什么? 提前谢谢大家。

最佳答案

这里有两个问题:

  1. 通过 BindingFlags.Public | BindingFlags.Instance 绑定(bind)
  2. 检查空值:propertyInfo.GetValue(applicationUser)?.ToString()Convert.ToString(propertyInfo.GetValue(applicationUser))

关于C# : propertyinfo always empty,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57956167/

相关文章:

c# - Unity,如何通过 ParameterOverride 传递 null?

c# - Linq 查询 Group By 和 contains

c# - MemberWiseClone 如何创建具有克隆属性的新对象?

java - 深度递归对象比较(再次)

java - 如何通过 "double.class"对象获取 "Double"

c# - 如何从 MVC3 中的 javascript 调用 Controller 方法?

c# - 在 ITextViewLine 上运行正则表达式(Visual Studio 扩展)

c# - 尝试使用 Visual Studio UI 测试器时出现 FailedToperformActionOnBlockedControlException

reflection - 我不明白Dart镜子中 “isSubtypeOf”的工作方式

java - Reflection + AOP - 通过调用调用方法时未拦截通知