C#:propertyinfo始终为空

西蒙妮西班牙

我在使用C#反射时遇到问题。我要反映的对象如下:

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

    public decimal CustomerId { get; set; }

    public string AlexaAccessToken { get; set; }

    public string GoogleHomeAccessToken { get; set; }
}

我用来反映的代码如下:

    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
  2. 检查空值:propertyInfo.GetValue(applicationUser)?.ToString()Convert.ToString(propertyInfo.GetValue(applicationUser))

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章