如何获取我们的属性设置的属性名称?

How to get name of property which our attribute is set?(如何获取我们的属性设置的属性名称?)

本文介绍了如何获取我们的属性设置的属性名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将在不向属性传递任何参数的情况下执行此操作!有可能吗?

I'm going to do this without passing any parameter to attribute! Is it possible?

class MyAtt : Attribute {
    string NameOfSettedProperty() {
        //How do this? (Would be MyProp for example)
    }
}

class MyCls {
    [MyAtt]
    int MyProp { get { return 10; } }
}

推荐答案

属性是应用于类型成员、类型本身、方法参数或程序集的元数据.为了让您能够访问元数据,您必须拥有原始成员本身才能使用 GetCustomAttributes 等,即您的 TypePropertyInfo 实例, FieldInfo

Attributes are metadata applied to members of a type, the type itself, method parameters, or the assembly. For you to have access to the metadata, you must have had the original member itself to user GetCustomAttributes etc, i.e. your instance of Type, PropertyInfo, FieldInfo etc.

在您的情况下,我实际上会将属性名称传递给属性本身:

In your case, I would actually pass the name of the property to the attribute itself:

public CustomAttribute : Attribute
{
  public CustomAttribute(string propertyName)
  {
    this.PropertyName = propertyName;
  }

  public string PropertyName { get; private set; }
}

public class MyClass
{
  [Custom("MyProperty")]
  public int MyProperty { get; set; }
}

这篇关于如何获取我们的属性设置的属性名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何获取我们的属性设置的属性名称?