2013-06-19 3 views
1

Прежде всего, это мое первое сообщение здесь, так что извините, если это неправильно или что-то, просто предупредите меня, что в следующий раз это будет лучше.Самый простой способ получить доступ к списку классов

Второй я говорю по-французски x).

Хорошо, это не проблема, но я хотел бы иметь лучший способ доступа к моим данным, которые хранятся в классе матери. Я знаю, что я не понимаю, позвольте мне показать вам, может быть, вы поймете.

Main.cs:

namespace Xahor 
{ 
    class Program 
    { 

     static void Main(string[] args) 
     { 
      TProduct test = new TProduct(); 

      test.FillData(1, "Apple", "4857", "A tasty apple.", "Green", false, true); 

      test.PrintData(); 
     } 
    } 
} 

TListNF.cs:

namespace Xahor 
{ 
    public class TListNF 
    { 
     public TListNF(int iProductID = 0, string sProductName = "", string sProductIDNum = "", string sProductDesc = "", string sColor = "", bool bMake = false, bool bCustom = false) 
     { 
      this.iProductID = iProductID; 
      this.sProductName = sProductName; 
      this.sProductIDNum = sProductIDNum; 
      this.sProductDesc = sProductDesc; 
      this.sColor = sColor; 
      this.bMake = bMake; 
      this.bCustom = bCustom; 
     } 

     public int iProductID { get; set; } 
     public string sProductName { get; set; } 
     public string sProductIDNum { get; set; } 
     public string sProductDesc { get; set; } 
     public string sColor { get; set; } 
     public bool bMake { get; set; } 
     public bool bCustom { get; set; } 

     protected List<TListNF> ItemList = new List<TListNF>(); 
    } 
} 

TProduct.cs:

namespace Xahor 
{ 
    class TProduct : TListNF 
    { 
     public void FillData(int iProductID, string sProductName, string sProductIDNum, string sProductDesc, string sColor, bool bMake, bool bCustom) 
     { 
      ItemList.Add(new TListNF(iProductID, sProductName, sProductIDNum, sProductDesc, sColor, bMake, bCustom)); 
     } 

     public void PrintData() 
     { 
      foreach (TListNF t in ItemList) 
      { 
       //Here where * is each of the accessor 
       Console.WriteLine(t.*.ToString()); 
       Console.WriteLine(t.*.ToString()); 
       ... 
      } 
     } 
    } 
} 

Так, поясню, что я не знаю, как сделать, чтобы получить более легкий доступ к геттеру, что это будет ormally быть Еогеаспом так каждый раз, когда мы входим в петле УАК т получить значение

Решенного

@Nair

Спасибо, я разобрался с постом

How to loop through all the properties of a class?

Но ваш ответ поможет кстати, если кому-то еще нужны такие вещи, как я, я использовал

foreach (PropertyInfo p in list.GetType().GetProperties()) 
       { 
        Console.WriteLine(p.Name + " : " + p.GetValue(list)); 
       } 
//Where list is the List<ClassName_With_Accesor> list; 
+0

Я думаю, что он не хочет писать в 20 раз «Console.WriteLine (t.PropXXXX.ToString())' и он ожидает некоторый путь к „Еогеасп над свойствами“. Это он Mokmeuh? – quetzalcoatl

+0

@ quetzalcoatl - если это так, то это дубликат, потому что на этот вопрос ответили много раз. – Hogan

+0

@ Хоган - да, я искал правильный дубликат прямо сейчас ..Он просто присоединился к SO, поэтому он очень вероятен, но, возможно, пусть сначала подтвердит;) – quetzalcoatl

ответ

0

Вы можете достичь этого путем отражения отдельных свойств в типе. Возможно, вам придется добавить более конструктивную логику, поскольку намерение состоит в том, чтобы показать эту идею.

foreach (TListNF t in ItemList) 
    { 
    foreach (PropertyInfo proInfo in t.GetType().GetProperties()) 
     { 
     Console.WriteLine(proInfo.GetGetMethod().Invoke(t,null).ToString()); 
     } 
    } 
0

Конечно, ответ @Nair правильный. Но обычно это плохая практика, чтобы использовать отражение для простых целей. Это связано с правами доступа вашего приложения и так далее. Вот еще два варианта, которые вы можете попробовать.

Вариант 1: Допустим свойства в собственном методе (см. TListNF.GetItemInfo). Недостаток: вам нужно добавить еще один выход в реализацию GetItemInfo каждый раз, когда вы добавляете другое свойство в свой класс TListNF. Преимущество: не использовать отражение вообще.

Вариант 2: Используйте собственный атрибут (см. MyInfoAttribute), чтобы отметить интересующие вас объекты. Обычно классы имеют еще несколько атрибутов, которые вы не хотите печатать. Преимущество: печатаются только отмеченные атрибуты: Недостаток: использование отражения.

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

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     [AttributeUsage(AttributeTargets.Property)] 
     public class MyInfoAttribute : Attribute 
     { 
     } 

     public class TListNF 
     { 
      public TListNF(int iProductID = 0, string sProductName = "", string sProductIDNum = "", string sProductDesc = "", string sColor = "", bool bMake = false, bool bCustom = false) 
      { 
       this.iProductID = iProductID; 
       this.sProductName = sProductName; 
       this.sProductIDNum = sProductIDNum; 
       this.sProductDesc = sProductDesc; 
       this.sColor = sColor; 
       this.bMake = bMake; 
       this.bCustom = bCustom; 
      } 

      [MyInfo] 
      public int iProductID { get; set; } 
      [MyInfo] 
      public string sProductName { get; set; } 
      [MyInfo] 
      public string sProductIDNum { get; set; } 
      [MyInfo] 
      public string sProductDesc { get; set; } 
      [MyInfo] 
      public string sColor { get; set; } 
      [MyInfo] 
      public bool bMake { get; set; } 
      [MyInfo] 
      public bool bCustom { get; set; } 

      protected List<TListNF> ItemList = new List<TListNF>(); 

      public IEnumerable<string> GetItemInfo() 
      { 
       yield return iProductID.ToString(); 
       yield return sProductName; 
       yield return sProductIDNum; 
       yield return sProductDesc; 
       yield return sColor; 
       yield return bMake.ToString(); 
       yield return bCustom.ToString(); 
      } 
     } 

     class TProduct : TListNF 
     { 
      public void FillData(int iProductID, string sProductName, string sProductIDNum, string sProductDesc, string sColor, bool bMake, bool bCustom) 
      { 
       ItemList.Add(new TListNF(iProductID, sProductName, sProductIDNum, sProductDesc, sColor, bMake, bCustom)); 
      } 

      public void PrintData() 
      { 
       foreach (TListNF item in ItemList) 
       { 
        foreach (string info in item.GetItemInfo()) 
         Console.WriteLine(info); 
       } 
      } 

      public void PrintDataReflection() 
      { 
       Type type = typeof(MyInfoAttribute); 

       foreach (TListNF item in ItemList) 
       { 
        foreach (PropertyInfo proInfo in item.GetType().GetProperties().Where(p => p.GetCustomAttributes(type, true).Length > 0)) 
        { 
         Console.WriteLine(proInfo.GetGetMethod().Invoke(item, null).ToString()); 
        } 
       } 
      } 
     } 

     static void Main(string[] args) 
     { 
      var test = new TProduct(); 

      test.FillData(1, "Apple", "4857", "A tasty apple.", "Green", false, true); 

      test.PrintData(); 
      test.PrintDataReflection(); 

      Console.ReadKey(); 
     } 
    } 
} 
+0

Спасибо, этот ответ тоже работает, но список огромен. Я просто разместил часть кода, но спасибо. Я знаю это сейчас: P – Mokmeuh

Смежные вопросы