gpt4 book ai didi

c# - 如何将 PropertyInfo[] 转换为 Dictionary

转载 作者:太空宇宙 更新时间:2023-11-03 10:56:15 26 4
gpt4 key购买 nike

实际上我需要我的类的属性显示在 mvc 下拉列表中。我正在使用反射来获取这些东西。但现在我的问题是将它们作为键值对显示在下拉列表中。

我正在使用下面的代码...

public static Dictionary<string,string> SetProperties()
{
Type T = Type.GetType("Entity.Data.Contact");
PropertyInfo[] resultcontactproperties = T.GetProperties();

ViewContactModel viewobj = new ViewContactModel();
viewobj.properties = resultcontactproperties;
Dictionary<string, string> dic = new Dictionary<string, string>();
return dic;
}

那么如何将它们转换为字典以在下面的下拉列表中显示它们...?

  @Html.DropDownListFor(m=>m.properties, new SelectList(Entity.Data.ContactManager.SetProperties(),"",""), "Select a Property")

Well this is my ViewContactModel

public class ViewContactModel
{

public List<Entity.Data.Contact> Contacts;
public int NoOfContacts { get; set; }
public Paging pagingmodel { get; set; }
public PropertyInfo[] properties { get; set; }
}

In the view I'm using this model

最佳答案

如果您必须使用字典并假设每个下拉项的名称和值是属性名称本身,您可以使用以下几行内容:

    public static Dictionary<string, string> GetProperties<T>(params string[] propNames)
{
PropertyInfo[] resultcontactproperties = null;
if(propNames.Length > 0)
{
resultcontactproperties = typeof(T).GetProperties().Where(p => propNames.Contains(p.Name)).ToArray();
}
else
{
resultcontactproperties = typeof(T).GetProperties();
}
var dict = resultcontactproperties.ToDictionary(propInfo => propInfo.Name, propInfo => propInfo.Name);
return dict;
}

@Html.DropDownListFor(m=>m.properties, new SelectList(
Entity.Data.ContactManager.GetProperties<Contact>(),"Key","Value"),
"Select a Property")

关于c# - 如何将 PropertyInfo[] 转换为 Dictionary<string,string>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19396074/

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