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 等,即您的 Type、PropertyInfo 实例, 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; }
}
这篇关于如何获取我们的属性设置的属性名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何获取我们的属性设置的属性名称?
基础教程推荐
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- WPF 模态进度窗口 2022-01-01
