Har*_*9pl 4 c# linq reflection linq-to-objects c#-4.0
我正在尝试做的是wirte linq表达式,它允许我List<PropertyInfo>通过Custom属性命令我的某个对象,例如:
public class SampleClass{
[CustomAttribute("MyAttrib1",1)]
public string Name{ get; set; }
[CustomAttribute("MyAttrib2",1)]
public string Desc{get;set;}
[CustomAttribute("MyAttrib1",2)]
public int Price{get;set;}
}
Run Code Online (Sandbox Code Playgroud)
CustomAttribute.cs:
public class CustomAttribute: Attribute{
public string AttribName{get;set;}
public int Index{get;set;}
public CustomAttribute(string attribName,int index)
{
AttribName = attribName;
Index = index;
}
}
Run Code Online (Sandbox Code Playgroud)
到目前为止,我能够从我的类中获取名为SampleClass的所有属性:
List<PropertyInfo> propertiesList = new List<PropertyInfo>((IEnumerable<PropertyInfo>)typeof(SampleClass).GetProperties());
Run Code Online (Sandbox Code Playgroud)
到目前为止,我尝试对此进行排序propertiesList(这顺便说一下):
var sortedPropertys = propertiesList
.OrderByDescending(
(x, y) => ((CustomAttribute) Attribute.GetCustomAttribute((PropertyInfo) x, typeof (CustomAttribute))).AttribName
.CompareTo((((CustomAttribute) Attribute.GetCustomAttribute((PropertyInfo) y, typeof (CustomAttribute))).AttribName ))
).OrderByDescending(
(x,y)=>((CustomAttribute) Attribute.GetCustomAttribute((PropertyInfo) x, typeof (CustomAttribute))).Index
.CompareTo((((CustomAttribute) Attribute.GetCustomAttribute((PropertyInfo) y, typeof (CustomAttribute))).Index)))
.Select(x=>x);
Run Code Online (Sandbox Code Playgroud)
输出列表应该是(我只用PropertyInfo.Name告诉它):
property name: Name,Price,Desc
Run Code Online (Sandbox Code Playgroud)
我的问题是:有可能这样做吗?如果是,我该如何正确地做到这一点?
如果你有一些问题请问(我会尽力回答每一个不确定因素).我希望对问题的描述就足够了.
谢谢你提前:)
var props = typeof(SampleClass)
.GetProperties()
.OrderBy(p => p.GetCustomAttributes().OfType<CustomAttribute>().First().AttribName)
.ThenBy(p => p.GetCustomAttributes().OfType<CustomAttribute>().First().Index)
.Select(p => p.Name);
var propNames = String.Join(", ", props);
Run Code Online (Sandbox Code Playgroud)
输出:名称,价格,描述
| 归档时间: |
|
| 查看次数: |
2268 次 |
| 最近记录: |