5

私がやろうとしているのはList<PropertyInfo>、たとえば次のようなカスタム属性でオブジェクトを並べ替えることができるwirtelinq式です。

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;}
}

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;
    }
}

これまでのところ、SampleClassという名前のクラスからすべてのプロパティを取得できました。

List<PropertyInfo> propertiesList = new List<PropertyInfo>((IEnumerable<PropertyInfo>)typeof(SampleClass).GetProperties());

私はこれまでこれをソートしようとしました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);

出力リストは次のようになります(PropertyInfo.Nameでのみ通知します):

property name: Name,Price,Desc

私の質問は:それを行うことは可能ですか?はいの場合、どうすればこれを適切に行うことができますか?

あなたがいくつかの質問をするならば、plsは尋ねます(私はすべての不確実性に答えるために最善を尽くします)。問題の説明で十分だと思います。

よろしくお願いします:)

4

2 に答える 2

11
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); 

出力:名前、価格、説明

于 2012-10-29T16:31:16.777 に答える
0

私はこれを読んでいたのは、xml属性を確認したかったので、エラーが発生したためです。この回答では、不要な属性も取得しているようです。それから私はうまくいくように見える何かを作りました、そして私はそれがいつか他の誰かを助けるかもしれないと自分自身に言います。

IOrderedEnumerable<PropertyInfo> Properties = typeof(FooClass).GetProperties()
                .Where(p => p.CustomAttributes.Any(y => y.AttributeType == typeof(XmlElementAttribute)))
                .OrderBy(g=> g.GetCustomAttributes(false).OfType<XmlElementAttribute>().First().Order);

于 2021-04-06T15:11:03.883 に答える