如何判断使用接口的实例变量是否应用了自定义属性

本文关键字:变量 实例 是否 应用 自定义属性 接口 何判断 判断 | 更新日期: 2023-09-27 18:35:46

我希望能够检查类实例上是否存在自定义属性,但我希望能够从该类的构造函数中执行该检查。看看这个伪代码:

namespace TestPackage
{
    public class MyAttribute : Attribute { }
    public interface IMyThing { }
    public class MyThing : IMyThing
    {
        private bool HasMyAttribute { get; set; }
        public MyThing()
        {
            if (/* some check for custom attribute */)
            {
                HasMyAttribute = true;
            }
        }
    }
    public class MyWrapper
    {
        [MyAttribute]
        private readonly IMyThing _myThing;
        public MyWrapper()
        {
            _myThing = new MyThing();
        }
    }
}

我有代码注释的 if 语句是我想填写的。这可能吗?

如何判断使用接口的实例变量是否应用了自定义属性

属性在代码中静态定义,因此是静态的,它们不绑定到实例。它们应用于类型或此类型的成员。

在您的情况下,您可以让包装器实现IMyThing并使用它而不是原始类型,然后将属性应用于类。

[MyAttribute]
public class MyWrapper : IMyThing
{
    private readonly IMyThing _myThing;
    public MyWrapper()
    {
        _myThing = new MyThing();
    }
    public void DoMyThingStuff()
    {
        _myThing.DoMyThingStuff();
    }
}

然后你可以像这样检查属性:

bool CheckAttribute(IMyThing myThing)
{
    Type t = myThing.GetType();
    return t.GetCustomAttributes(typeof(MyAttribute), false).Length > 0;
}

如果传递了原始类的对象,则会得到false .如果传递了包装器对象,则会得到true .

您还可以从原始类派生类,而不是创建包装器。

[MyAttribute]
public class MyDerived : MyThing
{
}

使用此构造函数:

public MyThing
{
                HasMyAttribute =false;
                foreach (MemberInfo item in this.GetType().GetCustomAttributes(false))
                {
                        if(item.Name=="MyAttribute")
                            HasMyAttribute =true;
                }
}