1

何らかの理由で、私はこれを取得していません。(以下のモデル例)私が書くと:

var property = typeof(sedan).GetProperty("TurningRadius");
Attribute.GetCustomAttributes(property,typeof(MyAttribute), false)

継承チェーンを検索したくないことを示しているにもかかわらず、呼び出しは MyAttribute(2) を返します。呼び出すために私が書くことができるコードを誰かが知っていますか

MagicAttributeSearcher(typeof(Sedan).GetProperty("TurningRadius"))

呼び出し中に何も返さない

MagicAttributeSearcher(typeof(Vehicle).GetProperty("TurningRadius"))

MyAttribute(1) を返しますか?


モデル例:

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

public class Car : Vehicle
{
    [MyAttribute(2)]
    public override int TurningRadius { get; set; }
}

public abstract class Vehicle
{
    [MyAttribute(1)]
    public virtual int TurningRadius { get; set; }
}
4

3 に答える 3

4

さて、追加情報を考えると、問題はGetProperty継承の変更が進んでいることだと思います。

への呼び出しを次のように変更した場合GetProperty:

PropertyInfo prop = type.GetProperty("TurningRadius",
    BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);

プロパティがオーバーライドされていない場合propは null になります。例えば:

static bool MagicAttributeSearcher(Type type)
{
    PropertyInfo prop = type.GetProperty("TurningRadius", BindingFlags.Instance | 
                                         BindingFlags.Public | BindingFlags.DeclaredOnly);

    if (prop == null)
    {
        return false;
    }
    var attr = Attribute.GetCustomAttribute(prop, typeof(MyAttribute), false);
    return attr != null;
}

trueこれは、次の場合にのみ返されます。

  • 指定された型はプロパティをオーバーライドしTurningRadiusます (または新しいものを宣言します)
  • プロパティにはMyAttribute属性があります。
于 2008-11-09T18:26:19.833 に答える
3

問題は、最初の行の Sedan オブジェクトからプロパティ TurningRadius を取得するときだと思います

var property = typeof(sedan).GetProperty("TurningRadius");

Sedan には独自のオーバーロードがないため、実際に得られるのは Car レベルで宣言された TurningRadius プロパティです。

したがって、その属性をリクエストすると、継承チェーンを上がらないようにリクエストした場合でも、car で定義されたプロパティが取得されます。これは、照会しているプロパティが Car で定義されているプロパティであるためです。

GetProperty を変更して、宣言メンバーのみを取得するために必要なフラグを追加する必要があります。DeclaredOnlyがすべきだと思います。

編集: この変更により、最初の行が null を返すことに注意してください。そのため、NullPointerExceptions に注意してください。

于 2008-11-09T18:25:42.253 に答える
1

これがあなたの求めているものだと思います - TurningRadius を Vehicle で抽象化し、Car でオーバーライドする必要があることに注意してください。それは大丈夫ですか?

using System;
using System.Reflection;

public class MyAttribute : Attribute
{
    public MyAttribute(int x) {}
}

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

public class Car : Vehicle
{
    public override int TurningRadius { get; set; }
}

public abstract class Vehicle
{
    [MyAttribute(1)]
    public virtual int TurningRadius { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        MagicAttributeSearcher(typeof(Sedan));
        MagicAttributeSearcher(typeof(Vehicle));
    }

    static void MagicAttributeSearcher(Type type)
    {
        PropertyInfo prop = type.GetProperty("TurningRadius");
        var attr = Attribute.GetCustomAttribute(prop, typeof(MyAttribute), false);
        Console.WriteLine("{0}: {1}", type, attr);
    }
}

出力:

Sedan:
Vehicle: MyAttribute
于 2008-11-07T23:35:39.663 に答える