Hca*_*tek 3 c# reflection collections
我需要一些帮助.我很反思.我们正在使用第三方api,它返回一个名为"AddressList"的类.它的公共属性字面上称为Address1,Address1Name,Address1Desc,Address2,Address2Name,Address2Desc,Address3,Address3Name,Address3Desc,... Address99,Address99Name,Address99Desc ..还有一些其他属性.我有一个名为"SimpleAddress"的类,它只有3个属性(地址,名称,描述).我想要做的是当我返回"AddressList"类时,我想通过AddressDesc99循环AddressDesc1 ...并且无论哪个都不为null或空,我想创建一个"SimpleAddress"的实例,填充它的属性,并将其添加到列表...有人能指出我正确的方向吗?显然,如果"AddressList"是某种集合,那会更好,但遗憾的是它不是.它是从大型机的返回字符串生成的.
谢谢你的帮助,〜在圣地亚哥
伊克.你可以这样做:
List<SimpleAddress> addresses = new List<SimpleAddress>();
string addressPropertyPattern = "Address{0}";
string namePropertyPattern = "Address{0}Name";
string descPropertyPattern = "Address{0}Desc";
for(int i = 1; i <= MAX_ADDRESS_NUMBER; i++)
{
System.Reflection.PropertyInfo addressProperty = typeof(AddressList).GetProperty(string.Format(addressPropertyPattern, i));
System.Reflection.PropertyInfo nameProperty = typeof(AddressList).GetProperty(string.Format(namePropertyPattern, i));
System.Reflection.PropertyInfo descProperty = typeof(AddressList).GetProperty(string.Format(descPropertyPattern, i));
SimpleAddress address = new SimpleAddress();
address.Address = (string)addressProperty.GetValue(yourAddressListObject, null);
address.Name = (string)nameProperty.GetValue(yourAddressListObject, null);
address.Description = (string)descProperty.GetValue(yourAddressListObject, null);
addresses.Add(address);
}
Run Code Online (Sandbox Code Playgroud)