获取对象和属性名称的类型名称?

时间:2012-09-23 18:16:08

标签: c# lambda expression

我需要函数,返回{obj type name}。{property name}。{property name} .. 例如:

class City {
    public string Name {get;set;}
}

class Country {
    public string Name {get;set;}
    public City MyCity {get;set;}
}

var myCountry = new Country() { 
    Name="Ukraine",
    MyCity = new City() {
        Name = "Kharkov"
    }
}

所以我的函数应该返回“{Country.Name}”或“{Country.MyCity.Name}”取决于输入参数。这样做的方法是什么?

3 个答案:

答案 0 :(得分:2)

答案 1 :(得分:0)

您没有发布有关要求的大量信息,但是,如果您知道对象类型,则无需使用反射,您可以使用is进行测试:

if(returnCity && myObject is Country) //I'm assuming that the input value is boolean but, you get the idea...
{
    return myObject.City.Name;
}
else
{
    return myObject.Name;
}

现在,如果你想使用Reflection,你可以在这些行中做点什么:

public static string GetNameFrom( object myObject )
{
    var t = myObject.GetType();
    if( t == typeof(Country) )
    {
        return ((Country)myObject).City.Name;
    }

    return ((City)myObject).Name;
}

或者,更通用的方法:

static string GetNameFrom( object myObject )
{
    var type = myObject.GetType();
    var city = myObject.GetProperty( "City" );
    if( city != null)
    {
        var cityVal = city.GetValue( myObject, null );
        return (string)cityVal.GetType().GetProperty( "Name" ).GetValue( cityVal, null );
    }

    return (string)type.GetProperty( "Name" ).GetValue( myObject, null );
}

答案 2 :(得分:0)

创建一个Printable facade并使用递归函数Print()。尝试抓住想法并修改具体任务的代码。希望,我的例子对你有所帮助。

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

namespace StackOverflow
{
    interface IPrintable
    {
        string Name { get; }
    }

    class City : IPrintable
    {
        public string Name { get; set; }
    }

    class Country : IPrintable
    {
        public string Name { get; set; }
        public City MyCity { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var myCountry = new Country()
            {
                Name = "Ukraine",
                MyCity = new City()
                 {
                     Name = "Kharkov"
                 }
            };

            Console.WriteLine(Print(myCountry, @"{{{0}}}"));
            Console.WriteLine(Print(new City()
            {
                Name = "New-York"
            }, @"{{{0}}}"));
        }

        private static string Print(IPrintable printaleObject, string formatter)
        {
            foreach (var prop in printaleObject.GetType().GetProperties())
            {
                object val = prop.GetValue(printaleObject, null);
                if (val is IPrintable)
                {
                    return String.Format(formatter, printaleObject.Name) + Print((IPrintable)val, formatter);
                }
            }
            return String.Format(formatter, printaleObject.Name);
        }
    }
}