如何在 C# 中创建自己的自定义属性

发布日期:2026-07-14 02:37:03  来源 : 杭州电子商务研究院    浏览量 :0
杭州电子商务研究院 发布日期:2026-07-14 02:37:03  
0

介绍

属性是一种以声明方式向代码添加元数据或信息的好方法。在使用 C# 的 .NET MVC 项目中,您可以找到用于向模型添加验证的属性。

      Required]
  [StringLength(50
    

属性有助于定义路线、HTTP 动词和权限。

      Route("Articles")]
[Authorize(Policy = "Editor")]
public class NewsArticleController : Controller
{
  [Route("")]
  [Route("List")]
  public IActionResult Index() { ... }

  [HttpPost("article/{id}")]
  public IActionResult Edit(int id) { ... }
}
    

如何创建简单属性

在 Visual Studio 中,开始使用属性的最快和最简单的方法是使用属性代码片段。您可以键入属性并按Tab键,让 Visual Studio 生成示例属性代码片段。该属性代码片段生成以下内容:

      System.AttributeUsage(AttributeTargets.All
    

这将生成一个继承自 Attribute 类的新类。该类不一定要以“Attribute”结尾,但这是一种惯例,可帮助其他人理解您的代码。

需要注意的一件重要事情是,该类本身具有一个属性,它会提出三个问题。

  1. 属性目标 - 此属性可应用于哪种类型的元素?AttributeTargets 是一个枚举,列出了可能的目标。
  2. 继承 - 如果将此属性应用于名为 AnimalClass 的类,并且从 AnimalClass 继承另一个名为 DogClass 的类,那么此属性也应该被继承吗?
  3. 允许多个- 是否可以在单个元素上设置此属性的多个实例?

Attribute 类可以接受必需的构造函数参数、可选的构造函数参数以及多个构造函数重载,就像 C# 中的大多数其他类一样。

使用与 Jason Roberts 的C# 属性:为您的代码 Pluralsight 课程增添强大功能和灵活性中类似的示例,我们可以创建一个属性,该属性在控制台应用程序中显示时会更改属性的颜色。

我们将修改 Visual Studio 生成的原始代码片段以创建颜色属性类。

      AttributeUsage(AttributeTargets.Property
    

这允许某人在属性上使用[Color][Color(ConsoleColor.Red)] 。如果使用时未向属性添加颜色,则将默认颜色设置为青色。

自定义属性经常会让人困惑,因为自定义属性需要两步操作。上面的代码只允许我们在属性上设置属性。现在我们需要在应用程序的其他地方添加逻辑来使用新属性。

      // First apply our new attributes to properties in a class
public class Dog
{
  [Color(ConsoleColor.Red)]
  public string Name { get; set; }
  [Color]
  public string Breed { get; set; }
  public int Age { get; set; }
}

// Next create a class to use those properties
public static class DogConsoleWriter
{
  public static void Line(Dog dog)
  {
    var defaultColor = Console.ForegroundColor;
    Console.Write("Name: ");
    // Here the console foreground is set to either the attribute color or a default color
    Console.ForegroundColor = GetPropertyColor(nameof(Dog.Name)) ?? defaultColor; ;
    Console.Write(dog.Name);
    Console.ForegroundColor = defaultColor;
    Console.WriteLine();

    Console.Write("Breed: ");
    Console.ForegroundColor = GetPropertyColor(nameof(Dog.Breed)) ?? defaultColor;
    Console.Write(dog.Breed);
    Console.ForegroundColor = defaultColor;
    Console.WriteLine();

    Console.Write("Age: ");
    Console.ForegroundColor = GetPropertyColor(nameof(Dog.Age)) ?? defaultColor;
    Console.Write(dog.Age);
    Console.ForegroundColor = defaultColor;
    Console.WriteLine();
  }

  // Here is the most important part
  private static ConsoleColor? GetPropertyColor(string propertyName)
  {
    // This uses C#'s reflection to get the attribute if one exists
    PropertyInfo propertyInfo = typeof(Dog).GetProperty(propertyName);
    ColorAttribute colorAttribute = (ColorAttribute)Attribute.GetCustomAttribute(propertyInfo, typeof(ColorAttribute));

    // If colorAttribute is not null, than a color attribute exists
    if(colorAttribute != null)
    {
        return colorAttribute.Color;
    }
    return null;
  }
}
    

现在控制台应用程序可以以类似的方式使用此类:

      DogConsoleWriter.Line(new Dog
{
  Name= "Astro",
  Breed= "Newfoundland"
});
    

让我们仔细看看完成最重要的步骤的GetPropertyColor方法。

      private static ConsoleColor? GetPropertyColor(string propertyName)
{
  PropertyInfo propertyInfo = typeof(Dog).GetProperty(propertyName);
  ColorAttribute colorAttribute = (ColorAttribute)Attribute.GetCustomAttribute(propertyInfo, typeof(ColorAttribute));

  if(colorAttribute != null)
  {
      return colorAttribute.Color;
  }
  return null;
}
    

此方法接受属性名称的字符串GetPropertyColor(string propertyName) 。该字符串通过使用nameof运算符nameof(Dog.Age)传递,以提供类型安全性。

然后,在方法的第一行中使用属性名称来获取指定类型的属性信息。本例中的类型是 Dog 类型。PropertyInfo propertyInfo = typeof(Dog).GetProperty(propertyName);

一旦获取 PropertyInfo,我们就可以检查它是否应用了任何属性。由于我们只关心 ColorAttribute,因此我们指定该类型。ColorAttribute colorAttribute = (ColorAttribute)Attribute.GetCustomAttribute(propertyInfo, typeof(ColorAttribute));

如果 GetCustomAttribute 找不到属性,它将返回 null。

属性的应用场景

您可以在 C# 中向以下任意一项添加属性:

  • 课程
  • 方法
  • 枚举
  • 活动
  • 字段
  • 特性
  • 结构
  • 参数
  • 构造函数
  • 代表
  • 接口
  • 返回值
  • 部件
  • 还有其他属性!

概括

添加属性可以帮助其他人快速了解您的代码想要完成的任务,而无需了解实现该任务的逻辑步骤。

要了解有关 C# 属性的更多信息,请查看 Jason Roberts 的完整课程C# 属性:为您的代码提供强大功能和灵活性。Jason 描述了多个属性用例示例以及创建和使用属性的更高级方法。

关于作者

Matt Ferderer 是一名软件开发人员,他在推特帖子博客上发布有关网络开发的内容

以上内容来自杭州电子商务研究院推送
分享到:

长按或扫码识别 分享给好友

长按或扫码识别 分享给好友
关于我们
热门推荐
合作伙伴
免责声明:本站部分资讯来源于网络,如有侵权请及时联系客服,我们将尽快处理
Copyright © 2025-2027 ToB产业网址导航 公安备案 浙公网安备33010602013138号 浙ICP备16025413号-9
支持 反馈 关注 数据