如何在自定义属性类中调用函数

本文关键字:调用 函数 自定义属性 | 更新日期: 2023-09-27 18:07:54

假设我有以下属性类:

 //Attribute Implementation 
    public abstract class TestAttribute : Attribute
    {
        public abstract void UpdateSomething(string s);
    }

    public class CustomAttTest : TestAttribute
    {
        private State state;
        public CustomAttTest(State state)
        {
            this.state = state;
        }
        public override void UpdateSomething(string s)
        {
            if (state.Equals(State.First))
            {
                Console.WriteLine("First State!! " + s);
            }
        }
    }
    public enum State
    {
        First, Second, Third
    }

我如何在属性类内调用Updatesomthing函数?下面是属性实现示例。

    public abstract class Vehicle
    {
        //Coode
    }
    [CustomAttTest(State.First)]
    public class Ferrari : Vehicle
    {
        //Code
    }

下面是完整的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            var foo = new Ferrari();
            //How do i call the UpdateSomething implemented insde the CustomAttTest attribute class?
        }
    }
    public abstract class Vehicle
    {
        //Coode
    }
    [CustomAttTest(State.First)]
    public class Ferrari : Vehicle
    {
        //Code
    }
    //Attribute Implementation 
    public abstract class TestAttribute : Attribute
    {
        public abstract void UpdateSomething(string s);
    }

    public class CustomAttTest : TestAttribute
    {
        private State state;
        public CustomAttTest(State state)
        {
            this.state = state;
        }
        public override void UpdateSomething(string s)
        {
            if (state.Equals(State.First))
            {
                Console.WriteLine("First State!! " + s);
            }
        }
    }
    public enum State
    {
        First, Second, Third
    }

}

如何在自定义属性类中调用函数

你需要使用反射:

foo.GetType().GetCustomAttribute<CustomAttTest>().UpdateSomething(...);

但是,您可能应该使用抽象方法或属性而不是属性。