2008-11-07 37 views
1

由于某种原因,我没有得到这个。 (下面的示例模式)如果我写:如何在获取属性时忽略继承链?

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

的通话将(2)表明,尽管我不希望搜索的继承链返回MyAttribute。有谁知道什么样的代码我可以写,这样调用

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

好吧,给予额外的信息 - 我相信问题是GetProperty是往上走的继承变化。

如果您更改您的来电GetProperty到:

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

然后prop将是无效的,如果属性不覆盖。例如:

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属性。
1

我觉得这是你以后在做什么 - 注意,我不得不做出TurningRadius在车辆的抽象和汽车覆盖。可以吗?

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 
+0

我不认为这个工程。该程序在测试轿车时找到了一个属性。这应该已经返回null。当你跑它时,它打印2行?如果是这样,它展示我遇到的问题。 – 2008-11-08 22:50:21

+0

它打印了两行,但是四色轿车在冒号后有一个空白,即你想要的。我会编辑答案是绝对完整的。 – 2008-11-08 23:26:22

3

我相信问题是,当你从轿车对象获得的财产TurningRadius在第一线

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

您实际得到的是TurningRadius属性在Car级别声明,因为Sedan没有自己的重载。

因此,当你要求它的属性,你得到在汽车中定义的,即使你要求不继承链往上走,因为要查询的属性是在汽车中定义的。

你应该改变的getProperty添加必要的标志,以只获得声明的成员。我相信DeclaredOnly应该做的。

编辑:请注意,这一变化将有第一线返回null,所以,要当心NullPointerException异常。