首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C#:propertyinfo总是空的

C#:propertyinfo总是空的
EN

Stack Overflow用户
提问于 2019-09-16 11:45:39
回答 1查看 311关注 0票数 2

我对c#反射有一个问题。我想要反映的对象如下:

代码语言:javascript
复制
public partial class ApplicationUser : IdentityUser
{
    public ApplicationUser()
    {
    }

    public decimal CustomerId { get; set; }

    public string AlexaAccessToken { get; set; }

    public string GoogleHomeAccessToken { get; set; }
}

我用来反映的代码如下:

代码语言:javascript
复制
    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总是空的。有什么问题吗?先谢谢大家。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-09-16 11:47:49

这里有两个问题:

  1. 通过BindingFlags.Public | BindingFlags.Instance绑定
  2. 检查空值:propertyInfo.GetValue(applicationUser)?.ToString()Convert.ToString(propertyInfo.GetValue(applicationUser))
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57956167

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档