e4r*_*dog 3 c# type-conversion visual-studio-2010
我可能在这里缺少基本知识,但我会去找它并问它.
让我们说我们有一个字符串数组:
ItemCode
ItemDescription
Run Code Online (Sandbox Code Playgroud)
我们有一个班级:
public class InventoryItem
{
public string ItemCode { get; set; }
public string ItemDescription { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我希望能够根据数组的值动态引用InventoryItem的属性.
我需要遍历数组并通过数组的当前字符串成员获取类的属性值.
我该怎么做?
你使用反射:
foreach (var name in propertyNames)
{
// Or instance.GetType()
var property = typeof(InventoryItem).GetProperty(name);
Console.WriteLine("{0}: {1}", name, property.GetValue(instance, null));
}
Run Code Online (Sandbox Code Playgroud)
看到: