实体类,例:
//自定义特性
public class StringRangeAttribute : BaseAttribute
{
public int Length { get; set; } //约束属性长度
public int Index { get; set; }
}
//实体类
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; }
}
[Serializable]
public class ProcessInquiry
{
/// <summary>
/// Process data item Length=10
/// </summary>
[StringRange(Length = 10)]
public string procdata { get; set; }
/// <summary>
/// Item SEQ No Length=4
/// </summary>
[StringRange(Length = 4)]
public string item_seq_no { get; set; }
}
我的解答思路和尝试过的方法
字符串:【1 50 4 61 3 5 123 789 130651 11112222222222222233333333333333】
public static void GetStrToEntity<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..Error("GetStrToEntity Error " + ex.Message);
}
}
//调用
ProcessInquiryReceive processInquiryReceive = new ProcessInquiryReceive()
{
trx_id = "1 5",
type_id = "0",
retcode1 = " 4 6",
sqlerrcode = "1 3 5 ",
procdata_id = "123 789 13",
arycnt1 = "065",
ary1 = new List<ProcessInquiry>
{
new ProcessInquiry(){ procdata="",item_seq_no=""},
new ProcessInquiry(){ procdata="",item_seq_no=""},
new ProcessInquiry(){procdata="",item_seq_no=""}
}
};
processInquiryReceive .GetStringToEntity(new list<string>());
这种调用方式,必须提前创建好指定数量的 List,但是数量是不固定的,有其他方法可以解决吗?