'C# How do I convert a string into an entity object that might contain a collection type
public class StringRangeAttribute : BaseAttribute
{
public int Length { get; set; } //property limitation of length
public int Index { get; set; }
public int CurrentLegth { get; set; }
}
My Class:
public class ProcessInquiryReceive:BaseOut
{
[StringRange(Length = 13, Index = 5)]
public string procdata_id { get; set; }
[StringRange(Length = 3, Index = 6)]
public string arycnt1 { get; set; }
[StringRange(Index = 7)]
public List<ProcessInquiry> ary1 { get; set; }
}
public class ProcessInquiry
{
[StringRange(Length = 10)]
public string procdata { get; set; }
[StringRange(Length = 4)]
public string item_seq_no { get; set; }
}
String:【1 50 4 61 3 5 123 789 130651 11112222222222222233333333333333】
My string To EntityObj function:
public static void StringToEntity<T>(this T t,string Str)
{
try
{
//获取类型
Type type = t.GetType();
//获取对象全部属性
PropertyInfo[] properties = type.GetProperties();
//进行属性排序
var PropertyByIndex = properties.OrderBy(p => (p.GetCustomAttributes(typeof(StringRangeAttribute), false).FirstOrDefault() as StringRangeAttribute).Index).ToArray();
foreach (var item in PropertyByIndex)
{
//获取该项 是否是泛型
var IsGenericType = item.PropertyType.IsGenericType;
//获取该项 实现或继承接口对象
var Lis = item.PropertyType.GetInterface("IEnumerable", false);
if (IsGenericType && Lis != null)
{
//将泛型集合中全部属性,转换成单个object对象
var ListVal = item.GetValue(t, null) as IEnumerable<object>;
if (ListVal == null)
continue;
//循环
foreach (var prop in ListVal)
{
prop.GetStrToEntity(Str);
}
}
else
{
//获取属性约束长度
int Len = (item.GetCustomAttributes(typeof(StringRangeAttribute), false).FirstOrDefault() as StringRangeAttribute).Length;
//GetCustomAttributes(typeof(StringRangeAttribute), false).FirstOrDefault() as StringRangeAttribute).Index
//设置长度
item.SetValue(t, Str.Substring(0,Len), null);
Str = Str.Substring(Len, Str.Length - Len);
}
}
}
catch (Exception ex)
{
Logger.IBMMQLogger.Error("GetStrToEntity Error " + ex.Message);
}
}
//main
ProcessInquiryReceive processInquiryReceive = new ProcessInquiryReceive()
{
ary1 = new List<ProcessInquiry>
{
new ProcessInquiry(){ },
new ProcessInquiry(){ },
new ProcessInquiry(){}
}
};
processInquiryReceive .StringToEntity(new list<string>());
For this method, however, the collection attributes must be created in advance to match the quantity. I don't know how many there are
ary1 = new List<ProcessInquiry>
{
new ProcessInquiry(){ procdata="",item_seq_no=""},
new ProcessInquiry(){ procdata="",item_seq_no=""},
new ProcessInquiry(){procdata="",item_seq_no=""}
}
Maybe you have other ways to convert strings to entity objects
Please help me thank you.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
