2017-07-19 34 views
0

开头的C#是真实的。我试图实现TypeDescriptor.GetProperties。在代码中,我继续获得一个空集合。我无法弄清楚为什么。试图让TypeDescriptor.GetProperties开始工作

任何帮助表示赞赏。谢谢。

public class SampleObjectToExportI 
{ 
    public Guid Id; 
    public DateTime Date; 
    public string StringValue; 
    public int NumberValue; 
    public bool BooleanValue; 
    public SampleObjectToExportI(Guid id, DateTime date, string stringValue, int numberValue, bool booleanValue) 
    { 
     this.Id = id; 
     this.Date = date; 
     this.StringValue = stringValue; 
     this.NumberValue = numberValue; 
     this.BooleanValue = booleanValue; 
    } 
} 
class Program 
{ 
    static void Main(string[] args) 
    { 
     var myList = new List<SampleObjectToExportI>(); 
     myList.Add(new SampleObjectToExportI(Guid.NewGuid(), DateTime.Now, "String4", 400, true)); 
     myList.Add(new SampleObjectToExportI(Guid.NewGuid(), DateTime.Now, "String5", 500, false)); 
     myList.Add(new SampleObjectToExportI(Guid.NewGuid(), DateTime.Now, "String6", 600, true)); 

     foreach (var sampleObjectToExport in myList) 
     { 
      foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(sampleObjectToExport)) 
      { 
       string name = descriptor.Name; 
       object value = descriptor.GetValue(sampleObjectToExport); 
       Console.WriteLine("{0}={1}", name, value); 
      } 
      //Console.WriteLine(sampleObjectToExport.NumberValue); 
     } 
    } 
} 

回答

2

你没有属性,如果你想那么这是语法:

public Guid Id { set; get; } 
public DateTime Date { set; get; } 
public string StringValue { set; get; } 
public int NumberValue { set; get; } 
public bool BooleanValue { set; get; } 

参考documentation获取更多信息。

另一种方式是让你的代码是和使用Type.GetFeilds()

foreach (var fieldInfo in typeof(SampleObjectToExportI).GetFields()) 
+0

伟大,感谢用户#!我知道的确是关于基础知识。这是一座陡峭的山丘。 – lcarpay