2017-06-29 59 views
-2

我想創建一些類,必須以某種方式查看(以我的示例中顯示的方式)。 某些類屬性本身就是類(或結構體)。 我想在我的類中編寫一個方法,該方法獲取所有屬性的屬性值,即結構並將它們寫入字符串。如何在類方法中獲得屬於類本身值的屬性

因此,這是我的課是這樣的:

public class car 
{ 
    public string brand { get; set; } 
    public tire _id { get; set; } 
    public string GetAttributes() 
    { 
     Type type = this.GetType(); 
     PropertyInfo[] properties = type.GetProperties(); 
     foreach(PropertyInfo propertyInfo in properties) 
     if (propertyInfo.PropertyType.ToString().Contains("_")) 
     { 
     //I want to write the actual value of the property here! 
     string nested_property_value = ... 
     return nested_property_value; 
     } 
    } 
} 

這是我的結構是這樣的:

public struct tire 
{ 
    public int id { get; set; } 
} 

這將是主程序:

tire mynewtire = new tire() 
{ 
    id = 5 
}; 

car mynewcar = new car() 
{ 
    _id = mynewtire 
}; 

任何人有一個想法如何創建GetAttributes-Methode?我一直試圖弄清楚現在這個年齡,但不去那裏...

+2

您的類型沒有任何屬性或屬性。 – Servy

+0

這是一個求職面試問題嗎? –

+0

您是否考慮使用JSON序列化將其轉換爲字符串? https://stackoverflow.com/questions/15843446/c-sharp-to-json-serialization-using-json-net – mjwills

回答

0

這段代碼會讓你開始。我建議你看看其他的序列化方法(如JSON)。

using System; 

namespace Test 
{ 
    public class car 
    { 
     public string brand { get; set; } 
     public tire _id { get; set; } 

     public string GetAttributes() 
     { 
      var type = this.GetType(); 
      var returnValue = ""; 
      var properties = type.GetProperties(); 
      foreach (var propertyInfo in properties) 
      { 
       // Look at properties of the car 
       if (propertyInfo.Name.Contains("_") && propertyInfo.PropertyType.IsValueType && 
        !propertyInfo.PropertyType.IsPrimitive) 
       { 
        var propValue = propertyInfo.GetValue(this); 

        var propType = propValue.GetType(); 
        var propProperties = propType.GetProperties(); 

        foreach (var propPropertyInfo in propProperties) 
        { 
         // Now get the properties of tire 
         // Here I just concatenate to a string - you can tweak this 
         returnValue += propPropertyInfo.GetValue(propValue).ToString(); 
        } 
       } 
      } 
      return returnValue; 
     } 
    } 

    public struct tire 
    { 
     public int id { get; set; } 
    } 

    public class Program 
    { 
     static void Main(string[] args) 
     { 
      var mynewtire = new tire() 
      { 
       id = 5 
      }; 

      var mynewcar = new car() 
      { 
       _id = mynewtire 
      }; 
      Console.WriteLine(mynewcar.GetAttributes()); 

      Console.ReadLine(); 
     } 
    } 
} 
+0

歡呼的伴侶,解決了我的問題!真的很感謝你花時間幫助我!正如我所說,我剛剛開始編寫兩個月前,所以我不知道csharp所提供的所有可能性!我也會研究你建議的其他方法。 – FlixFix

相關問題