我试图获取数组属性的属性类型
[Serializable]
public class Orders
{
public long OrderID { get; set; }
public string CustomerID { get; set; }
public int EmployeeID { get; set; }
public double Freight { get; set; }
public string ShipCountry { get; set; }
public string ShipCity { get; set; }
public Customer[] customer {get; set;}
}
public class Customer
{
public string OtherAddress { get; set; }
public int CustNum { get; set; }
}
我需要获得 Orders.Customer.OtherAddress 或 Orders.Customer.0.OtherAddress 索引的类型。 dataSource 是订单列表。
Type type = dataSource.GetElementType();
PropertyInfo propInfo = type.GetProperty("Customer");
DefaultMemberAttribute defaultMember =
(DefaultMemberAttribute)Attribute.GetCustomAttribute(propInfo.PropertyType,
typeof(DefaultMemberAttribute));
propInfo =
propInfo.PropertyType.GetProperty("CustNum" , new Type[] {
typeof(int) });
我该怎么办?
答案 0 :(得分:0)
OP,你的问题不是很清楚......"使用动态数据源"可能意味着很多不同的事情。但是,无论对数据源的引用是强类型对象,动态还是仅对象,引用的对象仍然是某种强类型类。除非由于某种原因您无法设置对其类型库的引用,否则您不需要使用任何反射。最多只需要一个简单的演员。有动力,甚至不需要。
例如,如果您有此界面:
public interface IRepository
{
dynamic GetListAsDynamic();
object GetListAsObject();
}
......以及实现它的类......
public class OrderRepository : IRepository
{
public dynamic GetListAsDynamic()
{
return new List<Order>
{
new Order
{
customer = new [] {new Customer { OtherAddress = "1234 Foo St" } }
}
};
}
public object GetListAsObject()
{
return new List<Order>
{
new Order
{
customer = new [] {new Customer { OtherAddress = "1234 Bar St" } }
}
};
}
}
您仍然可以在没有任何反映的情况下访问其他地址:
public class Program
{
public static void TestDynamic()
{
var repo = new OrderRepository();
var orders = repo.GetListAsDynamic();
var order = orders[0];
var customers = order.customer;
var customer = customers[0];
Console.WriteLine("And the customer dynamic's other address is.... '{0}'", customer.OtherAddress);
}
public static void TestObject()
{
var repo = new OrderRepository();
var orders = repo.GetListAsObject() as List<Order>;
var order = orders[0];
var customers = order.customer;
var customer = customers[0];
Console.WriteLine("And the customer object's other address is.... '{0}'", customer.OtherAddress);
}
public static void Main()
{
TestDynamic();
TestObject();
}
}
输出:
And the customer dynamic's other address is.... '1234 Foo St'
And the customer object's other address is.... '1234 Bar St'
答案 1 :(得分:0)
我认为你正在寻找一个&#34;泛型&#34;答案可以应用于其他未知的情况。但是,我不确定你的情况会如何通用/未知。我想出了这个&#34; OtherAddress&#34;但是你仍然需要知道一些字段名称。如果您需要完全通用的方法,则需要更广泛地提取各种属性。调试窗口中列出的类型是字符串。
public void GetTypeInfo()
{
Orders o = new Orders {customer = new Customer[] {new Customer()}};
dataSource.Add(o);
PropertyInfo info1 = dataSource[0].GetType().GetProperty("customer");
Array c = (Array) info1.GetValue(dataSource[0], null);
Type info2 = c.GetValue(0).GetType();
PropertyInfo info3 = info2.GetProperty("OtherAddress");
Debug.WriteLine("type| " + info3.PropertyType.Name);
}