使用内部逻辑创建自定义属性

creating custom attribute with logic inside

我这里有这个自定义属性,它执行一些逻辑

[AttributeUsage(AttributeTargets.All)]
public class CustomAttribute : Attribute
{
    public CustomAttribute ()
    {
        bool foo = false;
        if (foo)
            Console.WriteLine ("TRUE");
    }
}

然后我想在我的组件中使用它 class 像这样

[Custom]
public class Component
{
    public void Test()
    {
      console.log("test");
    }
}

所以我想要的是每次我创建该组件的实例时 class,它基本上会在我的属性中调用或执行该代码来执行一些逻辑,但问题是,它不会在我的自定义属性 class 中执行代码。我知道我做错了,有人知道怎么做吗?

实例化 class 时,它本身不会调用任何与您的属性关联的代码,甚至不会实例化它。属性仅在您使用反射调用它们时实例化。如果您希望在构造 class 时处理属性,则必须在 Component class 的构造函数中调用一个方法,该方法使用反射来分析 class 上的属性].

理想的方法是从具有构造函数逻辑的基础 class 继承:

public class Component : CustomBase
{
    public void Test()
    {
      console.log("test");
    }
}

public abstract class CustomBase
{
    public CustomBase()
    {
        bool foo = false;
        if (foo)
            Console.WriteLine ("TRUE");
    }
}

您需要致电:

object[] attributes = typeof(MyClass).GetCustomAttributes(true);

某处,因为这是将属性构造函数触发到 运行 的代码。 您可以在您的属性 class 中创建一个调用此行的方法,并在您的组件中调用属性方法。

正如 Jason 和 Cristina 所说,您需要考虑对具有自定义属性的代码进行反射。如果您阅读下面的代码(从第 18 行到第 24 行),您会看到一些注释掉的代码,其中列出了与某个类型关联的所有 CustomAttributes。

using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace CustomAttributeTest
{
    class Program
    {
        static void Main(string[] args)
        {
            var customCompo = new Component();
            customCompo.Test();

            //System.Reflection.MemberInfo info = typeof(Component);
            //object[] attributes = info.GetCustomAttributes(true);
            //for (int i = 0; i < attributes.Length; i++)
            //{
            //    System.Console.WriteLine(attributes[i]);

            //}
            Console.ReadLine();

        }
    }

    [CustomAttribute(true)]
    public class Component
    {
        public void Test()
        {

            System.Console.WriteLine("Component contructed");

            var member = typeof(Component);
            foreach (object attribute in member.GetCustomAttributes(true))
            {
                if (attribute is CustomAttribute)
                {
                    //noop
                }
            }


        }
    }


    [AttributeUsage(AttributeTargets.All)]
    public class CustomAttribute : Attribute
    {

        private bool _value;

        //this constructor specifes one unnamed argument to the attribute class
        public CustomAttribute(bool value)
        {
            _value = value;
            Console.WriteLine(this.ToString());

        }


        public override string ToString()
        {
            string value = "The boolean value stored is : " + _value;
            return value;
        }




    }



}