System.AttributeTargets.GenericParameter in C# : how do I use such an attribute?

允我心安 提交于 2020-05-13 05:09:16

问题


In C#, when specifying how an attribute class should be used, there is a GenericParameter value in the System.AttributeTargets enum. How can we apply such an attribute, what is the syntax ?

[System.AttributeUsage(System.AttributeTargets
public sealed class MyAnnotationAttribute : System.Attribute {
    public string Param { get; private set; }
    public MyAnnotationAttribute(string param) { Param = param; }
}

Same question goes for other exotic attribute targets, like System.AttributeTargets.Module (I don't even know how to declare modules other than the main module???), System.AttributeTargets.Parameter and System.AttributeTargets.ReturnValue.


回答1:


// Assembly and module
[assembly: AttributesTest.MyAnnotation("Assembly")]

[module: AttributesTest.MyAnnotation("Module")]

namespace AttributesTest
{
    // The attribute
    [System.AttributeUsage(System.AttributeTargets.All, AllowMultiple = true)]
    public sealed class MyAnnotationAttribute : System.Attribute
    {
        public string Param { get; private set; }
        public MyAnnotationAttribute(string param) { Param = param; }
    }

    // Types
    [MyAnnotation("Class")]
    public class SomeClass { }

    [MyAnnotation("Delegate")]
    public delegate int SomeDelegate(string s, float f);

    [MyAnnotation("Enum")]
    public enum SomeEnum { ValueOne, ValueTwo }

    [MyAnnotation("Interface")]
    public interface SomeInterface { }

    [MyAnnotation("Struct")]
    public struct SomeStruct { }

    // Members
    public class MethodsExample
    {
        [MyAnnotation("Constructor")]
        public MethodsExample() { }

        [MyAnnotation("Method")]
        public int SomeMethod(short s) { return 42 + s; }

        [MyAnnotation("Field")]
        private int _someField;

        [MyAnnotation("Property")]
        public int SomeProperty {
            [MyAnnotation("Method")] get { return _someField; }
            [MyAnnotation("Method")] set { _someField = value; }
        }

        private SomeDelegate _backingField;

        [MyAnnotation("Event")]
        public event SomeDelegate SomeEvent {
            [MyAnnotation("Method")] add { _backingField += value; }
            [MyAnnotation("Method")] remove { _backingField -= value; }
        }
    }

    // Parameters
    public class ParametersExample<T1, [MyAnnotation("GenericParameter")]T2, T3>
    {
        public int SomeMethod([MyAnnotation("Parameter")]short s) { return 42 + s; }
    }

    // Return value
    public class ReturnValueExample
    {
        [return: MyAnnotation("ReturnValue")]
        public int SomeMethod(short s) {
            return 42 + s;
        }
    }
}


来源:https://stackoverflow.com/questions/16721763/system-attributetargets-genericparameter-in-c-sharp-how-do-i-use-such-an-attri

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!