写一个CSharp特性的实例
时间: 2023-06-12 10:02:22 浏览: 52
好的,这里是一个基本的CSharp特性的实例:
```
using System;
[AttributeUsage(AttributeTargets.All)]
public class CustomAttribute : Attribute
{
private string message;
public CustomAttribute(string message)
{
this.message = message;
}
public string Message
{
get { return message; }
}
}
[Custom("This is a custom attribute")]
public class MyClass
{
// Class definition
}
```
这个例子定义了一个名为CustomAttribute的特性,它接受一个字符串参数作为构造函数的输入。然后,在MyClass类上应用了该特性,并将字符串“This is a custom attribute”传递给构造函数。
你可以使用反射来获取有关已应用的特性的信息。例如,以下代码将显示应用于Myclass类的自定义特性的消息:
```
CustomAttribute attribute = (CustomAttribute) Attribute.GetCustomAttribute(typeof(MyClass), typeof(CustomAttribute));
if (attribute != null)
{
Console.WriteLine(attribute.Message);
}
```