gpt4 book ai didi

C# : propertyinfo always empty

转载 作者:行者123 更新时间:2023-11-30 21:27:19 25 4
gpt4 key购买 nike

我对 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 绑定(bind) | BindingFlags.Instance
  2. 检查空值:propertyInfo.GetValue(applicationUser)?.ToString()Convert.ToString(propertyInfo.GetValue(applicationUser))

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com