2012-09-23 149 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); 
     } 
    } 
}