【问题标题】:Accessing a custom attribute from within an instanced object从实例化对象中访问自定义属性
【发布时间】:2015-06-09 20:33:51
【问题描述】:

我正在尝试找到一种方法来访问已从对象内的属性级别应用的属性,但我遇到了障碍。数据似乎存储在类型级别,但我需要它在属性级别。

这是我正在尝试制作的示例:

public class MyClass
{
    [MyAttribute("This is the first")]
    MyField First;
    [MyAttribute("This is the second")]
    MyField Second;
}

public class MyField
{
    public string GetAttributeValue()
    {
        // Note that I do *not* know what property I'm in, but this
        // should return 'this is the first' or 'this is the second',
        // Depending on the instance of Myfield that we're in.
        return this.MyCustomAttribute.value;  
    }
}

【问题讨论】:

标签: c# attributes


【解决方案1】:

属性不是这样使用的。属性存储在包含该属性的类对象中,而不是在类中声明的成员对象/字段中。

由于您希望每个成员都是唯一的,所以感觉更像是带有MyField 的成员数据,由构造函数传入。

如果您一心想要使用属性,您可以在构造函数中添加代码,该代码对每个附加了属性的成员使用反射,尝试将其实例数据设置为您想要的,但您需要以确保您的所有 MyField 对象均已完全构造。

或者,你可以让你的 setter 看起来像这样:

private MyField _first;
[MyAttribute("This is the first")]
public MyField First {
    get { return _first; }
    set {
        _first = value;
        if (_first != null) {
            _first.SomeAttribute = GetMyAttributeValue("First");
        }
    }
 }

 private string GetMyAttributeValue(string propName)
 {
     PropertyInfo pi = this.GetType().GetPropertyInfo(propName);
     if (pi == null) return null;
     Object[] attrs = pi.GetCustomAttributes(typeof(MyAttribute));
     MyAttribute attr =  attrs.Length > 0 ? attrs[0] as MyAttribute : null;
     return attr != null ? attr.Value : null;
 }

【讨论】:

  • 不是我想听到的,但不幸的是,这似乎是故事的结局。在我看来,您可以将自定义属性添加到特定类的各个属性,但您不能在类的实例中使用它们来修改行为,这对我来说似乎很奇怪。我知道这种情况非常适合类上的属性,我只是想解决一个不允许我为此使用属性的休眠错误。感谢您的快速回答,Plinth!
  • 如果您将属性视为伴随类的元数据,这是有道理的。您可以将属性放在类、字段、属性或方法上,然后可以从定义这些元素的Type 对象访问该数据。
  • 我明白你在说什么,但这正是为什么它对我来说没有意义。如果属性是类级别的元数据,那么为什么它们会在实例级别生效(或不生效)?例如:[Required(true)] public int IsRequired;公共 int 不需要;只有一个 instance 整数将具有此属性,而不是两者都具有。因此,如果元数据在类级别......我可能只是误解了一切,但在我看来,该属性是在实例级别应用的,否则两个整数都会受到影响。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-12
  • 2011-11-13
  • 1970-01-01
  • 2016-06-05
  • 2021-09-24
  • 2012-06-15
相关资源
最近更新 更多