如何从对象实例在C#中的自定义属性 [英] How to get a custom attribute from object instance in C#

查看:440
本文介绍了如何从对象实例在C#中的自定义属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有一类称为测试与一个属性名为标题与自定义属性:

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

public class Test
{
    [DatabaseField("title")]
    public string Title { get; set; }
}

和一个名为DbField扩展方法。我想知道如果从一个对象实例得到一个自定义属性甚至可以在C#。

And an extension method called DbField. I am wondering if getting a custom attribute from an object instance is even possible in c#.

Test t = new Test();
string fieldName = t.Title.DbField();
//fieldName will equal "title", the same name passed into the attribute above

可以这样做?

Can this be done?

推荐答案

下面是一种方法。该扩展方法的工作原理,但它不是那么容易。我创建了一个前pression,然后检索自定义属性。

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<T>(this T obj, Expression<Func<T, string>> 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; }

    }
}

这篇关于如何从对象实例在C#中的自定义属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆