Skip to main content
 首页 » 编程设计

c#之访问自定义属性中的声明类

2024年02月06日18小虾米

我创建了一个自定义属性,我想在其中访问自定义属性属性的声明类。

例如:

public class Dec 
{ 
    [MyCustomAttribute] 
    public string Bar {get;set;} 
} 

在这里,我想(在 MyCustomAttribute 的类中)获取声明类 (Dec) 的类型。 这有可能吗?

编辑:感谢大家的回复。我今天学到了一些新东西。

请您参考如下方法:

正如我所写的,仅当您使用 type.GetCustomAttributes() 请求属性时,属性才会被实例化,但那时您已经拥有了 Type。你唯一能做的就是:

[AttributeUsage(AttributeTargets.Property)] 
public class MyCustomAttribute : Attribute  
{ 
    public void DoSomething(Type t)  
    { 
 
    } 
} 
 
public class Dec  
{ 
    [MyCustomAttribute] 
    public string Bar { get; set; } 
} 
 
// Start of usage example 
 
Type type = typeof(Dec); 
var attributes = type.GetCustomAttributes(true); 
var myCustomAttributes = attributes.OfType<MyCustomAttribute>(); 
// Shorter (no need for the first var attributes line):  
// var myCustomAttributes = Attribute.GetCustomAttributes(type, typeof(MyCustomAttribute), true); 
 
 
foreach (MyCustomAttribute attr in myCustomAttributes)  
{ 
    attr.DoSomething(type); 
} 

因此将类型作为参数传递。