C# Feature 添加Attributes
时间: 2023-10-06 22:12:29 浏览: 43
在 C# 中,你可以为类、方法、属性或其他程序实体添加属性(Attributes)。属性是一种元数据,可以提供关于程序实体的额外信息,并可以在运行时通过反射来访问。要为一个程序实体添加属性,你需要使用方括号 [] 将属性放在目标实体的上方。
以下是一个简单的示例,展示如何在 C# 中添加属性:
```csharp
using System;
// 自定义属性类
public class MyAttribute : Attribute
{
public string Description { get; set; }
public MyAttribute(string description)
{
Description = description;
}
}
// 使用自定义属性
[MyAttribute("这是一个示例类")]
public class MyClass
{
[MyAttribute("这是一个示例方法")]
public void MyMethod()
{
// 方法的实现
}
}
class Program
{
static void Main(string[] args)
{
// 获取类上的属性
var classAttribute = (MyAttribute)Attribute.GetCustomAttribute(typeof(MyClass), typeof(MyAttribute));
Console.WriteLine(classAttribute.Description);
// 获取方法上的属性
var methodInfo = typeof(MyClass).GetMethod("MyMethod");
var methodAttribute = (MyAttribute)Attribute.GetCustomAttribute(methodInfo, typeof(MyAttribute));
Console.WriteLine(methodAttribute.Description);
}
}
```
在上述示例中,我们定义了一个名为 `MyAttribute` 的自定义属性类。然后,我们将 `MyAttribute` 属性应用于 `MyClass` 类和其中的 `MyMethod` 方法。在 `Main` 方法中,我们使用反射来获取并打印这些属性的描述信息。
请注意,属性可以具有不同的参数和返回类型,这取决于你的需求。你可以根据自己的需要定义和使用属性。