62 lines
1.0 KiB
Plaintext
62 lines
1.0 KiB
Plaintext
When defining custom attributes, ``++System.AttributeUsageAttribute++`` must be used to indicate where the attribute can be applied. This will determine its valid locations in the code.
|
|
|
|
|
|
== Noncompliant Code Example
|
|
|
|
[source,text]
|
|
----
|
|
using System;
|
|
|
|
namespace MyLibrary
|
|
{
|
|
|
|
public sealed class MyAttribute :Attribute // Noncompliant
|
|
{
|
|
string text;
|
|
|
|
public MyAttribute(string myText)
|
|
{
|
|
text = myText;
|
|
}
|
|
public string Text
|
|
{
|
|
get
|
|
{
|
|
return text;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
----
|
|
|
|
|
|
== Compliant Solution
|
|
|
|
[source,text]
|
|
----
|
|
using System;
|
|
|
|
namespace MyLibrary
|
|
{
|
|
|
|
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Delegate)]
|
|
public sealed class MyAttribute :Attribute
|
|
{
|
|
string text;
|
|
|
|
public MyAttribute(string myText)
|
|
{
|
|
text = myText;
|
|
}
|
|
public string Text
|
|
{
|
|
get
|
|
{
|
|
return text;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
----
|
|
|