5

だから、私が持っている場合:

public class Sedan : Car 
{
    /// ...
}

public class Car : Vehicle, ITurn
{
    [MyCustomAttribute(1)]
    public int TurningRadius { get; set; }
}

public abstract class Vehicle : ITurn
{
    [MyCustomAttribute(2)]
    public int TurningRadius { get; set; }
}

public interface ITurn
{
    [MyCustomAttribute(3)]
    int TurningRadius { get; set; }
}

次のようなことを行うためにどのような魔法を使用できますか:

[Test]
public void Should_Use_Magic_To_Get_CustomAttributes_From_Ancestry()
{
    var property = typeof(Sedan).GetProperty("TurningRadius");

    var attributes = SomeMagic(property);

    Assert.AreEqual(attributes.Count, 3);
}

両方

property.GetCustomAttributes(true);

Attribute.GetCustomAttributes(property, true);

1 つの属性のみを返します。インスタンスは、MyCustomAttribute(1) で構築されたものです。これは期待どおりに動作しないようです。

4

2 に答える 2

2
object[] SomeMagic (PropertyInfo property)
{
    return property.GetCustomAttributes(true);
}

アップデート:

私の上記の答えはうまくいかないので、次のようなことを試してみませんか:

public void Should_Use_Magic_To_Get_CustomAttributes_From_Ancestry()
{

    Assert.AreEqual(checkAttributeCount (typeof (Sedan), "TurningRadious"), 3);
}


int checkAttributeCount (Type type, string propertyName)
{
        var attributesCount = 0;

        attributesCount += countAttributes (type, propertyName);
        while (type.BaseType != null)
        {
            type = type.BaseType;
            attributesCount += countAttributes (type, propertyName);
        }

        foreach (var i in type.GetInterfaces ())
            attributesCount += countAttributes (type, propertyName);
        return attributesCount;
}

int countAttributes (Type t, string propertyName)
{
    var property = t.GetProperty (propertyName);
    if (property == null)
        return 0;
    return (property.GetCustomAttributes (false).Length);
}
于 2008-11-07T19:51:26.513 に答える
1

これはフレームワークの問題です。インターフェイス属性は、GetCustomAttributes によって無視されます。このブログ投稿のコメントを参照してください http://hyperthink.net/blog/getcustomattributes-gotcha/#comment-65

于 2009-02-24T10:50:19.977 に答える