以方法为目标的属性不起作用。代码如下。可能是什么问题呢?
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);
}
}
}
最佳答案
因为您是从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
关于c# - 结合使用ContextAttribute和方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/990139/