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

时间:2014-06-09 02:56:07

标签: c# custom-attributes

假设我有以下属性类。

 //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
    }


}

1 个答案:

答案 0 :(得分:1)

你需要使用反射:

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

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