我将在不向属性传递任何参数的情况下执行此操作!有可能吗?
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; }
}
这篇关于如何获取我们的属性设置的属性名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!