C# Extension method for checking attributes

后端 未结 6 1408
南笙
南笙 2021-02-02 17:44

Sorry if this is a stupid noob question please be gentle with me I\'m trying to learn...

I want to test against the attribute methods of things like models and controlle

6条回答
  •  一个人的身影
    2021-02-02 18:29

    You're looking for the Reflection class - it allows you to examine a passed object.

    But frankly other than a learning exercise this is what Interfaces exist for, if you want there to be a field called Required in a model, or a method called IsRequired in a controller than implement in an interface and require that interface be implemented.

    Specifically for attributes see here:

    Type t = something;
    System.Console.WriteLine("Author information for {0}", t);
    System.Attribute[] attrs = System.Attribute.GetCustomAttributes(t);  // reflection
    
    foreach (System.Attribute attr in attrs)
    {
        if (attr is Author)
        {
            Author a = (Author)attr;
                System.Console.WriteLine("   {0}, version {1:f}", a.GetName(), a.version);
        }
    }
    

提交回复
热议问题