代码练习在 C# 中得到一个 object (包含匿名对象)的属性和属性值

本文介绍了一种在C#中获取匿名对象属性名称及值的方法,并通过代码示例展示了如何使用自定义Inspect方法来获取不同类型的匿名对象的属性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码能说明一切:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DearBruce.ConAppTest
{
enum Color
{
Red,
Green,
Blue
}

struct KeyValuePair<TKey, TValue>
{
public TKey Key { get; set; }

public TValue Value { get; set; }
}

class Student
{
public Guid Id { get; set; }

public string Name { get; set; }

public DateTime Birthday { get; set; }
}

class Program
{
static void Main(string[] args)
{
string[] items = new string[]
{
AnonymousObject.Inspect(null), // (null)
AnonymousObject.Inspect(new {}), // no properties
AnonymousObject.Inspect(new
{
Id = Guid.NewGuid(),
Name = "张三",
Birthday = new DateTime(1987,5,6)
}),
// { Id: 2117c3cf-f99c-4636-9390-900fea0c085d, Name: 张三, Birthday: 1987/5/6 0:00:00 }
AnonymousObject.Inspect(Color.Red), // no properties
AnonymousObject.Inspect(
new KeyValuePair<Guid, string>()
{
Key = Guid.NewGuid(),
Value = "HelloWorld"
}),
// { Key: 67faae54-b6bd-4702-9175-54f6291a7199, Value: HelloWorld }
AnonymousObject.Inspect(
new Student
{
Id = Guid.NewGuid(),
Name = "张三",
Birthday = new DateTime(1987, 5, 6)
})
// { Id: 8e189b10-0702-4927-8f65-81c86dcc33bd, Name: 张三, Birthday: 1987/5/6 0:00:00 }
};
CommonHelper.Show(items);
}
}

public static class AnonymousObject
{
public static string Inspect(object obj)
{
if (obj == null)
{
return "(null)";
}

object[] args = Enumerable.Empty<Object>().ToArray();
IEnumerable<string> values = obj.GetType()
.GetProperties()
.Select(prop => String.Format("{0}: {1}", prop.Name, prop.GetValue(obj, args)));

if (!values.Any())
{
return "(no properties)";
}

return "{ " + values.Aggregate((left, right) => left + ", " + right) + " }";
}
}
}

 

运行截图:


 也许你还会喜欢:C# 中 动态获得或设置一个对象的值

谢谢浏览!

转载于:https://www.cnblogs.com/Music/archive/2012/03/27/get-property-name-and-value-from-a-object-or-a-anonymous-object-in-csharp.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值