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

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

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)