C#检测AnonymousType新{名称=值,}并转换成字典<字符串,对象>字符串、字典、对象、名称

2023-09-03 09:04:57 作者:▍歐美範er的美男胚子

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

如果它是一个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>.