Sad*_*egh 33 c# reflection attributes
我将在不传递属性的任何参数的情况下执行此操作!可能吗?
class MyAtt : Attribute {
string NameOfSettedProperty() {
//How do this? (Would be MyProp for example)
}
}
class MyCls {
[MyAtt]
int MyProp { get { return 10; } }
}
Run Code Online (Sandbox Code Playgroud)
tuk*_*aef 143
使用.NET 4.5中的CallerMemberNameAttribute:
public CustomAttribute([CallerMemberName] string propertyName = null)
{
// ...
}
Run Code Online (Sandbox Code Playgroud)
属性是应用于类型成员、类型本身、方法参数或程序集的元数据。为了使您能够访问元数据,您必须拥有原始成员本身的用户GetCustomAttributes等,即您的Type、PropertyInfo等FieldInfo的实例。
在你的例子中,我实际上会将属性的名称传递给属性本身:
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; }
}
Run Code Online (Sandbox Code Playgroud)