将ContextAttribute与Method一起使用

时间:2009-06-13 06:39:37

标签: c# custom-attributes

目标方法的属性不起作用。代码如下。可能是什么问题?

using System;
namespace AttributeProgram
{

    class Program:ContextBoundObject
    {
        [TestAttribute("Hello")]
        public void Print()
        {
            Console.WriteLine("How are you?");
        }
        static void Main(string[] args)
        {
            Program obj = new Program();
            obj.Print();
        }
    }

    [AttributeUsage(AttributeTargets.Method)]
    class TestAttribute : System.Runtime.Remoting.Contexts.ContextAttribute
    {
        public TestAttribute(string Name) : base("Test")
        {
            Console.WriteLine(Name);
        }
    }
}

1 个答案:

答案 0 :(得分:4)

因为您继承自ContextAttribute,只能根据文档应用于类:

[SerializableAttribute]
[ComVisibleAttribute(true)]
[AttributeUsageAttribute(AttributeTargets.Class)]
[SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.Infrastructure)]
[SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags = SecurityPermissionFlag.Infrastructure)]
public class ContextAttribute : Attribute, 
    IContextAttribute, IContextProperty