代码之家  ›  专栏  ›  技术社区  ›  pwxcoo

如何在c对象(如javascript)中获取属性?

c#
  •  0
  • pwxcoo  · 技术社区  · 6 年前

    public string getName(object ob)
    {
        // TODO: if object has "Name" attribute, return "Name".Value, else return null;
    }
    

    string result1 = getName(new {Name = "jack", Age = 12})     // result1 = "jack"
    string result2 = getName(new {Age = 12})      // result2 = null
    

    我知道用JavaScript或其他动态语言很容易实现…我很好奇它是否能在C中实现?

    3 回复  |  直到 6 年前
        1
  •  5
  •   Rumpelstinsk    6 年前

    是的,你可以。看看 Reflection

    public string getName(object ob)
    {
        var type = ob.GetType();
        if (type.GetProperty("Name") == null) return null;
        else return type.GetProperty("Name").GetValue(ob, null);
    }
    
        2
  •  2
  •   SᴇM    6 年前

    实现这一点有几种方法。例如,使用反射。它需要一个行代码:

    public static string GetName(object ob) =>
        ob.GetType().GetProperty("Name")?.GetValue(ob)?.ToString();
    

    public static string GetName(object ob)
    {
        return ob.GetType().GetProperty("Name")?.GetValue(ob)?.ToString();
    }
    

    甚至可以将对象序列化为JSON或XML,然后尝试从中获取值:

    public static string GetName(object obj)
    {
        string json = JsonConvert.SerializeObject(obj);
        string result = JsonConvert.DeserializeAnonymousType(json, new { Name = "" })?.Name;
        return result;
    }
    
        3
  •  1
  •   AD8    6 年前

    虽然这可能适用于您的需要,但它可能不是最好的解决方案,正如grek40和damien_在下面的评论中指出的,由于一些限制。

    原始答案:

    http://rextester.com/DQOBW76322

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text.RegularExpressions;
    
    namespace Rextester
    {
        public class Program
        {
            public static void Main(string[] args)
            {
    
                string result1 = getName(new {Name = "jack", Age = 12});    // result1 = "jack"
                string result2 = getName(new {Age = 12});
    
                Console.WriteLine(result1);
                Console.WriteLine(result2);
            }
    
            public static string getName(object obj)
            {
                var testData = obj.GetType().GetProperties().ToDictionary(p => p.Name, p => p.GetValue(obj).ToString());
    
                if(testData.Any(d => d.Key == "Name")){
                    return testData["Name"];
                }
    
                return null;
            }
        }
    }