2

例:私はこのクラスを持っています

public class MyClass
{
    private string propHead;
    private string PropHead { get; set; }

    private int prop01;
    private int Prop01 { get; set; }

    private string prop02;
    private string Prop02 { get; set; }

    // ... some more properties here

    private string propControl;
    private string PropControl { get; }  // always readonly
}

propHead と propControl を除外する必要があります。propControl を除外するには:

MyClass mc = new MyClass();
PropertyInfo[] allProps = mc.GetType().GetProperties().Where(x => x.CanWrite).ToArray();

さて、すべてが同じレベルのアクセシビリティを共有している場合、どのように propHead を除外できますか? propHead に特別な属性を追加して、他の属性から除外できるようにする方法はありますか。プロパティ名は、クラスごとに常に異なります。

どんな提案も非常に高く評価されます。

4

1 に答える 1

1

これが最も簡単な方法です。

MyClass mc = new MyClass();
PropertyInfo[] allProps = mc.GetType()
    .GetProperties()
    .Where(x => x.Name != "propHead" && x.Name != "propControl")
    .ToArray();

しかし、より汎用的なソリューションを探している場合は、これを試すことができます

public class CustomAttribute : Attribute
{
    ...
}

MyClass mc = new MyClass();
PropertyInfo[] allProps = mc.GetType()
    .GetProperties()
    .Where(x => x.GetCustomAttributes(typeof(CustomAttribute)).Length > 0)
    .ToArray();
于 2013-03-18T05:31:34.807 に答える