zoukankan      html  css  js  c++  java
  • 代码练习在 C# 中得到一个 object (包含匿名对象)的属性和属性值

    代码能说明一切:

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

    运行截图:

  • 相关阅读:
    [luoguP2221] [HAOI2012]高速公路(线段树)
    SICP:对数步数内迭代计算幂的函数
    python__tkinter之listbox&button
    C陷阱与缺陷 之 各种知识技巧
    ACM && Find Minimum in Rotated Sorted Array
    windows编程一些小知识
    Linux_C pthread 关于多线程一个简单的程序
    ACM&贪心算法
    Linux_C socket 数据报之client, server.c
    Linux_C socket 数据报之一些辅助函数
  • 原文地址:https://www.cnblogs.com/chenzhao/p/2667856.html
Copyright © 2011-2022 走看看