gpt4 book ai didi

c# - C# : how do I use such an attribute? 中的 System.AttributeTargets.GenericParameter

转载 作者:太空狗 更新时间:2023-10-30 01:06:01 24 4
gpt4 key购买 nike

在 C# 中,当指定应如何使用属性类时,System.AttributeTargets 枚举中有一个 GenericParameter 值。我们如何应用这样的属性,语法是什么?

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

同样的问题也适用于其他外来属性目标,例如 System.AttributeTargets.Module(我什至不知道如何声明主模块以外的模块???),System .AttributeTargets.ParameterSystem.AttributeTargets.ReturnValue

最佳答案

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

关于c# - C# : how do I use such an attribute? 中的 System.AttributeTargets.GenericParameter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16721763/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com