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

时间:2011-02-02 20:29:40

标签: c# c#-4.0 custom-attributes

我已经尝试了很多次,但我仍然无法理解自定义属性的用法(我已经通过了很多链接)。

任何人都可以向我解释一个带代码的自定义属性的基本示例吗?

4 个答案:

答案 0 :(得分:243)

首先编写一个派生自Attribute的类:

public class MyCustomAttribute: Attribute
{
    public string SomeProperty { get; set; }
}

然后你可以用这个属性装饰任何东西(类,方法,属性......):

[MyCustomAttribute(SomeProperty = "foo bar")]
public class Foo
{

}

最后你会用反射来获取它:

var customAttributes = (MyCustomAttribute[])typeof(Foo).GetCustomAttributes(typeof(MyCustomAttribute), true);
if (customAttributes.Length > 0)
{
    var myAttribute = customAttributes[0];
    string value = myAttribute.SomeProperty;
    // TODO: Do something with the value
}

您可以使用AttributeUsage属性限制可以应用此自定义属性的目标类型:

/// <summary>
/// This attribute can only be applied to classes
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public class MyCustomAttribute : Attribute

有关属性的重要事项:

  • 属性是元数据。
  • 它们在编译时中被装入程序集,这对于如何设置其属性具有非常严重的影响。只接受常量(在编译时已知)值
  • 了解自定义属性的唯一方法是使用Reflection。因此,如果您不在运行时使用反射来获取它们并使用自定义属性装饰某些东西,那么预计不会发生太多事情。
  • 创建属性的时间是不确定的。它们由CLR实例化,你完全无法控制它。

答案 1 :(得分:88)

虽然创建自定义Attribute的代码非常简单,但了解属性是非常重要的:

属性是编译到程序中的元数据。属性本身不会向类,属性或模块添加任何功能,只会添加数据。但是,使用反射,可以利用这些属性来创建功能。

因此,举个例子,让我们看一下来自Validation Application BlockEnterprise Library。如果你看一个代码示例,你会看到:

    /// <summary>
    /// blah blah code.
    /// </summary>
    [DataMember]
    [StringLengthValidator(8, RangeBoundaryType.Inclusive, 8, RangeBoundaryType.Inclusive, MessageTemplate = "\"{1}\" must always have \"{4}\" characters.")]
    public string Code { get; set; }

从上面的代码片段中,人们可能会猜测,无论何时更改,Code都将始终根据Validator的规则进行验证(在示例中,至少包含8个字符,最多8个字符)。但事实是,属性不执行任何操作,只会向属性添加元数据。

但是,企业库有Validation.Validate方法可以查看您的对象,并且对于每个属性,它将检查内容是否违反了属性通知的规则。

所以,这就是你应该如何考虑属性的方法 - 一种向你的代码添加数据的方法,这些方法可能会被其他方法/类/等稍后使用。

答案 2 :(得分:19)

利用/复制Darin Dimitrov's great response,这是如何访问属性而不是类的自定义属性:

[类datatype]的装饰属性:

test_index

取出它:

datatype

您可以将其抛入循环并使用反射来访问类Foo每个属性上的此自定义属性:

[MyCustomAttribute(SomeProperty = "This is a custom property")]
public string MyProperty { get; set; }

非常感谢你,Darin !!

答案 3 :(得分:1)

简短的答案是在c#中创建一个属性,您只需要从Attribute类继承它,就这样:)

但是在这里,我将详细解释属性:

基本上,属性是类,我们可以使用它们将逻辑应用于程序集,类,方法,属性,字段...

在.Net中,Microsoft提供了一些预定义的属性,例如“过时”或“验证属性”,例如([[Required],[StringLength(100)],[Range(0,999.99)])),此外,我们还提供了诸如ActionFilters之类的属性asp.net对于将我们期望的逻辑应用于代码非常有用(如果您热衷于学习,请阅读this关于动作过滤器的文章)

另一方面,您可以通过AttibuteUsage在属性上应用一种配置。

  [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = true)]

当用AttributeUsage装饰属性类时,您可以告诉C#编译器我将在哪里使用该属性:我将在类,属性或程序集上使用它,而我的属性是允许在定义的目标(类,程序集,属性等)上使用多次?!

关于属性的定义之后,我将向您展示一个示例: 想象一下,我们想在大学里定义一门新课,而我们只希望大学里的管理员和硕士可以定义一个新课,好吗?

namespace ConsoleApp1
{
    /// <summary>
    /// All Roles in our scenario
    /// </summary>
    public enum UniversityRoles
    {
        Admin,
        Master,
        Employee,
        Student
    }

    /// <summary>
    /// This attribute will check the Max Length of Properties/fields
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = true)]
    public class ValidRoleForAccess : Attribute
    {
        public ValidRoleForAccess(UniversityRoles role)
        {
            Role = role;
        }
        public UniversityRoles Role { get; private set; }

    }


    /// <summary>
    /// we suppose that just admins and masters can define new Lesson
    /// </summary>
    [ValidRoleForAccess(UniversityRoles.Admin)]
    [ValidRoleForAccess(UniversityRoles.Master)]
    public class Lesson
    {
        public Lesson(int id, string name, DateTime startTime, User owner)
        {
            var lessType = typeof(Lesson);
            var validRolesForAccesses = lessType.GetCustomAttributes<ValidRoleForAccess>();

            if (validRolesForAccesses.All(x => x.Role.ToString() != owner.GetType().Name))
            {
                throw new Exception("You are not Allowed to define a new lesson");
            }
            
            Id = id;
            Name = name;
            StartTime = startTime;
            Owner = owner;
        }
        public int Id { get; private set; }
        public string Name { get; private set; }
        public DateTime StartTime { get; private set; }

        /// <summary>
        /// Owner is some one who define the lesson in university website
        /// </summary>
        public User Owner { get; private set; }

    }

    public abstract class User
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public DateTime DateOfBirth { get; set; }
    }


    public class Master : User
    {
        public DateTime HireDate { get; set; }
        public Decimal Salary { get; set; }
        public string Department { get; set; }
    }

    public class Student : User
    {
        public float GPA { get; set; }
    }



    class Program
    {
        static void Main(string[] args)
        {

            #region  exampl1

            var master = new Master()
            {
                Name = "Hamid Hasani",
                Id = 1,
                DateOfBirth = new DateTime(1994, 8, 15),
                Department = "Computer Engineering",
                HireDate = new DateTime(2018, 1, 1),
                Salary = 10000
            };
            var math = new Lesson(1, "Math", DateTime.Today, master);

            #endregion

            #region exampl2
            var student = new Student()
            {
                Name = "Hamid Hasani",
                Id = 1,
                DateOfBirth = new DateTime(1994, 8, 15),
                GPA = 16
            };
            var literature = new Lesson(2, "literature", DateTime.Now.AddDays(7), student);
            #endregion

            ReadLine();
        }
    }


}

在编程的现实世界中,也许我们不使用这种方法来使用属性,我之所以这么说是因为它在使用属性方面具有教育意义