C#检测AnonymousType新{名称=值,}并转换成字典<字符串,对象> [英] C# Detecting AnonymousType new{name=value,} and convert into Dictionary<string,object>

查看:156
本文介绍了C#检测AnonymousType新{名称=值,}并转换成字典<字符串,对象>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检测如果一个对象被创建匿名像新的一样{名称=值,}

如果它是一个AnonymousType,应该加它的属性名称/值成

 词典<字符串,对象>
 

这是我砍死在一起自己:

  VAR名称=名称;

VAR OBJ =新{名称=新的对象()};

VAR查找=新字典<字符串,对象>();


如果(obj.GetType()Name.StartsWith(&其中;> f__AnonymousType。))
{
    的foreach(在obj.GetType()VAR财产。GetProperties中())
    {
        查找[property.Name] = property.GetValue(OBJ,NULL);
    }
}
其他
{
    查找[名] = OBJ;
}
 

我想知道是否有检测AnonymousTypes更好/更快的方式, 或者,如果有更好/更快的方法来转储对象的属性名称/值成

 词典<字符串,对象>
 

解决方案

要获取对象的所有属性,它的值转换为词典,您可以结合的LINQ的动力与反思的对象。

您可以使用 Enumerable.ToDictionary 方式:

  VAR DIC = obj.GetType()
             .GetProperties()
             .ToDictionary(P => p.Name,P => p.GetValue(OBJ,NULL));
 

这将返回你词典<字符串,对象>

I need to detect if an object was created anonymously like new{name=value,}

if it is an AnonymousType, it should add it's properties names/values into a

Dictionary<string,object>

This is what I hacked together myself:

var name="name";

var obj = new { name = new object(), };

var lookup = new Dictionary<string,object>();


if(obj.GetType().Name.StartsWith("<>f__AnonymousType"))
{
    foreach (var property in obj.GetType().GetProperties())
    {
        lookup[property.Name] = property.GetValue(obj, null);
    }
}
else
{
    lookup[name]=obj;
}

I was wondering if there is a better/faster way of detecting AnonymousTypes, or if there is a better/faster way to dump an object's properties names/values into a

Dictionary<string,object>

解决方案

To get all the properties of an object, with its values into a Dictionary, you can couple the power of Linq to Objects with Reflection.

You can use the Enumerable.ToDictionary method:

var dic = obj.GetType()
             .GetProperties()
             .ToDictionary(p => p.Name,  p=> p.GetValue(obj, null));

This will return you a Dictionary<string, object>.

这篇关于C#检测AnonymousType新{名称=值,}并转换成字典&LT;字符串,对象&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆