2012-09-23 146 views
1

我需要的功能,即返回{obj类型名称} {属性名} {属性名} .. 例如:。获取对象和属性名称的类型名称?

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}”取决于输入参数。有什么办法呢?

+0

可以告诉你输入的输出如何影响?你的意见是什么? –

+0

的Cuong乐,当 “myCountry.Name”,然后 “{国家}。{NAME}”,当 “myCountry.MyCity.Name”,然后 “{国家}。{MyCity}。{NAME}”,并使其SENS? – Yara

+0

更好告诉你的方法定义什么是你输入的,什么是我们的输出 –

回答

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; 
} 

现在,如果你想使用反射,你可以做这些线路中的东西:

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

不是我谁只是投你失望没有发表评论,但不得已的这种做法。如果避免反射是期望的,那么一个接口或一个属性是更好的设计和方法更长远的保障 –

+0

完全同意你的观点,但是,从我给了他一个“简单”的解决方案的问题来看,可能是所有他需要... – VoidMain

+1

这个网站上有些人有点快速脱颖而出。加强这一点可能是明智的,这是快速和肮脏的方法。看到这里有足够的答案,我一直把你推回到一个平坦的零:) –

0

创建IPrintable外观和使用递归函数打印()。尝试抓住这个想法并修改具体任务的代码。希望,我的榜样将会对你有所帮助。

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