gpt4 book ai didi

c# - 获取属性时如何忽略继承链?

转载 作者:太空宇宙 更新时间:2023-11-03 18:20:18 45 4
gpt4 key购买 nike

出于某种原因,我没有得到这个。 (下面的示例模型)如果我写:

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

最佳答案

好的,考虑到额外信息 - 我认为问题在于 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属性(property)(或宣布新属性(property))
  • 该属性(property)有 MyAttribute属性。

关于c# - 获取属性时如何忽略继承链?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/273949/

45 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com