How to get a custom attribute from object instance in C#

前端 未结 6 1203
眼角桃花
眼角桃花 2020-12-05 07:40

Let\'s say I have a class called Test with one property called Title with a custom attribute:

public class Test
{
    [DatabaseField(\"title\")]
    public s         


        
6条回答
  •  猫巷女王i
    2020-12-05 08:13

    Here is an approach. The extension method works, but it's not quite as easy. I create an expression and then retrieve the custom attribute.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Linq.Expressions;
    
    namespace ConsoleApplication1
    {
        public class DatabaseFieldAttribute : Attribute
        {
            public string Name { get; set; }
    
            public DatabaseFieldAttribute(string name)
            {
                this.Name = name;
            }
        }
    
        public static class MyClassExtensions
        {
            public static string DbField(this T obj, Expression> value)
            {
                var memberExpression = value.Body as MemberExpression;
                var attr = memberExpression.Member.GetCustomAttributes(typeof(DatabaseFieldAttribute), true);
                return ((DatabaseFieldAttribute)attr[0]).Name;
            }
        }
    
        class Program
        {
            static void Main(string[] args)
            {
                var p = new Program();
                Console.WriteLine("DbField = '{0}'", p.DbField(v => v.Title));
    
            }
            [DatabaseField("title")]
            public string Title { get; set; }
    
        }
    }
    

提交回复
热议问题