我需要获得班级中所有成员的类型。
public class Order
{
public int OrderID { get; set; }
public int EmployeeID { get; set; }
public string CustomerID { get; set; }
public DateTime OrderDate { get; set; }
public bool Verified { get; set; }
public Order(int orderId, int empId, string custId, DateTime orderDate, bool verify)
{
this.OrderID = orderId;
this.EmployeeID = empId;
this.CustomerID = custId;
this.OrderDate = orderDate;
this.Verified = verify;
}
}
和我通过List
添加的类的值 List<dynamic> dy = new List<dynamic>();
dy.Add(new { OrderID = 11, EmployeeID = 5, CustomerID = "ALFKI", OrderDate = new DateTime(2015,01, 10), Verified = true });
dy.Add(new { OrderID = 12, EmployeeID = 4, CustomerID = "CDSAW", OrderDate = new DateTime(2015, 02, 12), Verified = true });
dy.Add(new { OrderID = 13, EmployeeID = 6, CustomerID = "ASDFG", OrderDate = new DateTime(2015, 03, 13), Verified = true });
dy.Add(new { OrderID = 14, EmployeeID = 3, CustomerID = "XSDAF", OrderDate = new DateTime(2015, 04, 14), Verified = false });
dy.Add(new { OrderID = 15, EmployeeID = 2, CustomerID = "MNHSD", OrderDate = new DateTime(2015, 05, 15), Verified = true });
dy.Add(new { OrderID = 16, EmployeeID = 1, CustomerID = "OKJHG", OrderDate = new DateTime(2015, 06, 16), Verified = false });
return dy;
要获取字段类型,我尝试使用以下代码。
Type type = dataSource.GetElementType();
Type t = typeof(object);
t = type.GetProperty("OrderDate").PropertyType;
它抛出一个空表达式错误。
这里OrderDate是DateTime对象。
Type type = dataSource.GetType();
这一行返回System.object。
尝试获取OrderDate字段时。
type.GetProperty(filterString).PropertyType;
返回Null,如何解决此问题。
答案 0 :(得分:0)
首先,如果你想获得指定类型的所有字段和属性类型,你应该知道一些事情。
每个房产都拥有自己的支持领域。对于自动生成的属性public int MeProperty { get; set; }
,支持字段的名称为<MeProperty>k__BackingField
。
了解这一点,您应该考虑提取FieldInfo
而不是PropertyInfo
。
另一件事是你假设GetProperty
方法甚至会提取隐藏的(private
,protected
等...)成员,这是完全错误的。它希望您使用BindingFlags
枚举指定可访问性级别。
获得所有这些知识后,您可以使用以下方法提取属性的所有字段:
var fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
之后,您可以枚举并获取字段类型:
var fieldTypes = fields.Select(f => f.FieldType);
现在,fieldTypes
IEnumerable<Type>
包含type
字段中指定的每种字段类型。
真正的问题是你想要实现自动映射器,它从动态类型创建你定义的类型。为此,我建议您使用my answer on this question
中的解决方案修改强>
使用此代码:
class Program
{
static void Main()
{
foreach(var field in typeof(Order).GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public))
{
Console.WriteLine(field.Name);
}
}
public class Order
{
public int OrderID { get; set; }
public int EmployeeID { get; set; }
public string CustomerID { get; set; }
public DateTime OrderDate { get; set; }
public bool Verified { get; set; }
public Order(int orderId, int empId, string custId, DateTime orderDate, bool verify)
{
this.OrderID = orderId;
this.EmployeeID = empId;
this.CustomerID = custId;
this.OrderDate = orderDate;
this.Verified = verify;
}
}
}
您应该具有相同的输出:
<OrderID>k__BackingField
<EmployeeID>k__BackingField
<CustomerID>k__BackingField
<OrderDate>k__BackingField
<Verified>k__BackingField