• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

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

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

代码能说明一切:

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) + " }"; } } }

 

运行截图:

 

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C#通过接口或者父类可以调用子类的方法或者属性吗?发布时间:2022-07-10
下一篇:
C#读取XML文件的基类实现发布时间:2022-07-10
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap