c# - 如何将类转换为 Dictionary<string,string>?

标签 c# asp.net dictionary

我可以将 Class 转换成 Dictionary 吗?

在字典中,我希望我的类属性作为,并将特定属性的值作为

假设我的类(class)是

public class Location
{
    public string city { get; set; }
    public string state { get; set; }
    public string country { get; set;
}

现在假设我的数据是

city = Delhi
state = Delhi
country = India

现在你可以很容易地理解我的意思了!

我想做一个字典!该词典应该是这样的:

Dictionary<string,string> dix = new Dictionary<string,string> ();
dix.add("property_name", "property_value");

我可以取值!但是我怎样才能获得属性名称(不是值)呢?

我应该编写什么代码来创建它动态?这应该适用于我想要的每个类(class)。

你可以这样理解这个问题:

如何获取特定类的属性列表?

现在我再次解释我对词典的渴望之一!这个问题从我的previous question的回答中浮现在脑海中!!

最佳答案

这是秘诀:1 次反射,1 次 LINQ-to-Objects!

 someObject.GetType()
     .GetProperties(BindingFlags.Instance | BindingFlags.Public)
          .ToDictionary(prop => prop.Name, prop => (string)prop.GetValue(someObject, null))

自从我发布这个答案后,我检查过很多人认为它有用。我邀请所有寻找这个简单解决方案的人查看另一个问答,我在其中将其概括为扩展方法:Mapping object to dictionary and vice versa

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

相关文章:

python - 如何将字典分配给另一个字典?

c# - 如何获取数组的计数?在C#

c# - 根据分布 Accord.net 对数字数组进行分类

c# - Element .net MAUI 的宽度和高度始终为 NaN

c# - 如何强制浏览器使用版本控制重新加载缓存的静态文件?

C++如何更改 map 元素的值

swift 4。字典合并

c# - Xamarin 中的 BackgroundWorker 与 Android 服务

asp.net - 永远不会调用 ValueProvider

javascript - 如何在firefox上使用parent.parent.document.getElementById? ASP.NET