C#自定义Attribute值的获取是开发中会经常用到的,一般我们的做法也就是用反射进行获取的,代码也不是很复杂。

1、首先有如下自定义的Attribute

     [AttributeUsage(AttributeTargets.All)]
public sealed class NameAttribute : Attribute
{
private readonly string _name; public string Name
{
get { return _name; }
} public NameAttribute(string name)
{
_name = name;
}
}

  2、定义一个使用NameAttribute的类

[Description("Customer Information")]
[Name("customer_info")]
public class CustomerInfo
{
[Name("name")]
public string Name { get; set; } [Name("address")]
public string Address;
}

 

  3、获取CustomAttributes类上的"dept"也就很简单了

         private static string GetName()
{
var type = typeof(CustomAttributes); var attribute = type.GetCustomAttributes(typeof(NameAttribute), false).FirstOrDefault(); if (attribute == null)
{
return null;
} return ((NameAttribute)attribute).Name;
}

  以上代码就可以简单的获取,类上的Attribute的值了,但是需求往往不是这么简单的,不仅要获取类头部Attribute上的值,还要获取字段Address头部Attribute上的值。有的同学可能就觉得这还不简单呀,直接上代码

         private static string GetAddress()
{
var type = typeof (CustomAttributes); var fieldInfo = type.GetField("Address");
if (fieldInfo == null)
{
return null;
} var attribute = fieldInfo.GetCustomAttributes(typeof(NameAttribute), false).FirstOrDefault(); if (attribute == null)
{
return null;
} return ((NameAttribute) attribute).Name;
}

  上面代码就是获取Address字段头部上的Attribute值了。虽然我们是获取到了我们想要的,但是我们发现这样做是不是太累了,如果又扩展一个自定义的Attribute,或者又在一个新的属性或字段上标上Attribute时,我们又要写一段代码来实现我想要的,这些严重代码违反了DRY的设计原则。我们知道获取Attribute是通过反射来取的,Attribute那个值又是不变的,这样就没必要每次都要进行反射来获取了。基于以上两点代码进行了如下的优化,优化后的代码如下:

 using System;
using System.Collections.Concurrent;
using System.Reflection; public static class CustomAttributeExtensions
{
/// <summary>
/// Cache Data
/// </summary>
private static readonly ConcurrentDictionary<string, object> Cache = new ConcurrentDictionary<string, object>(); /// <summary>
/// 获取CustomAttribute Value
/// </summary>
/// <typeparam name="TAttribute">Attribute的子类型</typeparam>
/// <typeparam name="TReturn">TReturn的子类型</typeparam>
/// <param name="sourceType">头部标有CustomAttribute类的类型</param>
/// <param name="attributeValueAction">取Attribute具体哪个属性值的匿名函数</param>
/// <returns>返回Attribute的值,没有则返回null</returns>
public static TReturn GetCustomAttributeValue<TAttribute, TReturn>(this Type sourceType, Func<TAttribute, TReturn> attributeValueAction)
where TAttribute : Attribute
{
return _getAttributeValue(sourceType, attributeValueAction, null);
} /// <summary>
/// 获取CustomAttribute Value
/// </summary>
/// <typeparam name="TAttribute">Attribute的子类型</typeparam>
/// <typeparam name="TReturn">TReturn的子类型</typeparam>
/// <param name="sourceType">头部标有CustomAttribute类的类型</param>
/// <param name="attributeValueAction">取Attribute具体哪个属性值的匿名函数</param>
/// <param name="propertyName">field name或property name</param>
/// <returns>返回Attribute的值,没有则返回null</returns>
public static TReturn GetCustomAttributeValue<TAttribute, TReturn>(this Type sourceType, Func<TAttribute, TReturn> attributeValueAction, string propertyName)
where TAttribute : Attribute
{
return _getAttributeValue(sourceType, attributeValueAction, propertyName);
} #region private methods private static TReturn _getAttributeValue<TAttribute, TReturn>(Type sourceType, Func<TAttribute, TReturn> attributeFunc, string propertyName)
where TAttribute : Attribute
{
var cacheKey = BuildKey<TAttribute>(sourceType, propertyName);
var value = Cache.GetOrAdd(cacheKey, k => GetValue(sourceType, attributeFunc, propertyName));
if (value is TReturn) return (TReturn)Cache[cacheKey];
return default(TReturn);
} private static string BuildKey<TAttribute>(Type type, string propertyName) where TAttribute : Attribute
{
var attributeName = typeof(TAttribute).FullName;
if (string.IsNullOrEmpty(propertyName))
{
return type.FullName + "." + attributeName;
} return type.FullName + "." + propertyName + "." + attributeName;
} private static TReturn GetValue<TAttribute, TReturn>(this Type type, Func<TAttribute, TReturn> attributeValueAction, string name)
where TAttribute : Attribute
{
TAttribute attribute = default(TAttribute);
if (string.IsNullOrEmpty(name))
{
attribute = type.GetCustomAttribute<TAttribute>(false);
}
else
{
var propertyInfo = type.GetProperty(name);
if (propertyInfo != null)
{
attribute = propertyInfo.GetCustomAttribute<TAttribute>(false);
}
else
{
var fieldInfo = type.GetField(name);
if (fieldInfo != null)
{
attribute = fieldInfo.GetCustomAttribute<TAttribute>(false);
}
}
} return attribute == null ? default(TReturn) : attributeValueAction(attribute);
} #endregion
}

  优化后的代码:

  把不同的代码用泛型T,Fun<TAttribute,TReturn>来处理来减少重复的代码;
  把取过的Attribute值存到一个ConcurrentDictionary中,下次再来取时,如果有则直接取ConcurrentDictionary中的值,如果没有才通过反射来取相应的Attribute值,这样大大的提高效率;

  调用方法也更加的简单了,代码如下:

            var customerInfoName = typeof(CustomerInfo).GetCustomAttributeValue<NameAttribute, string>(x => x.Name);
var customerAddressName = typeof(CustomerInfo).GetCustomAttributeValue<NameAttribute, string>(x => x.Name, "Address");
var customerInfoDesc = typeof(CustomerInfo).GetCustomAttributeValue<DescriptionAttribute, string>(x => x.Description); Console.WriteLine("CustomerInfo Name:" + customerInfoName);
Console.WriteLine("customerInfo >Address Name:" + customerAddressName);
Console.WriteLine("customerInfo Desc:" + customerInfoDesc);

  运行结果:

  如果你有什么好的或不好的意见欢迎拍砖!

  谢谢大家的建议,己经更新(2019/11/21)

  Code:Download

C#自定义Attribute值的获取与优化的更多相关文章

  1. .net c#获取自定义Attribute

    前言: 在c#开发中,有时候我们需要读取 Attribute中的信息(关于Attribute , 我自己把他理解成一个可以为类,属性标记的东西,这个标记可以为你提供一些关于类,方法,属性的额外信息) ...

  2. 转:C#制作ORM映射学习笔记一 自定义Attribute类

    之前在做unity项目时发现只能用odbc连接数据库,感觉非常的麻烦,因为之前做web开发的时候用惯了ORM映射,所以我想在unity中也用一下ORM(虽然我知道出于性能的考虑这样做事不好的,不过自己 ...

  3. 【MVC 笔记】MVC 自定义 Attribute 属性中的猫腻

    原想在 MVC Action 上加一个自定义 Attribute 来做一些控制操作,最先的做法是在自定 Attribute 中定义一个属性来做逻辑判断,可惜事与愿违,这个属性值居然会被缓存起来,于是于 ...

  4. Django项目:CRM(客户关系管理系统)--14--06PerfectCRM实现King_admin注册功能获取内存优化处理

    <th >{% get_app_name admin_class.model %}{{ admin_class }} </th> #kingadmin_tags.py # —— ...

  5. XsdGen:通过自定义Attribute与反射自动生成XSD

    前言 系统之间的数据交互往往需要事先定义一些契约,在WCF中我们需要先编写XSD文件,然后通过自动代码生成工具自动生成C#对象.对于刚刚接触契约的人来说,掌握XMLSpy之类的软件之后确实比手写XML ...

  6. 自定义Attribute 服务端校验 客户端校验

    MVC 自定义Attribute 服务端校验 客户端校验/* GitHub stylesheet for MarkdownPad (http://markdownpad.com) *//* Autho ...

  7. 从值栈获取List集合

    -------------------siwuxie095 从值栈获取 List 集合 1.具体步骤 (1)在 Action 中向值栈放 List 集合 (2)在 JSP 页面中从值栈获取 List ...

  8. 使用c#特性,给方法或类打自定义标签再反射获取

    给方法打自定义标签再反射获取 1.自定义特性类 using System; using System.Collections; using System.Collections.Generic; // ...

  9. map自定义键值类型

    map自定义键值类型 改变Map的默认比较方式 https://www.cnblogs.com/zjfdlut/archive/2011/08/12/2135698.html 大家知道,STL中的ma ...

随机推荐

  1. Pycharm在创建py文件时,如何自动添加文件头注释(类似于钩子特性)?

    在每次新建一个py文件的时候 1 如何自动添加/usr/bin/env python2 自动添加 coding=utf8 操作方法: File->settings->Editor-> ...

  2. linux常用命令(5)rmdir命令

    rmdir是常用的命令,该命令的功能是删除空目录,一个目录被删除之前必须是空的.(注意,rm - r dir命令可代替rmdir,但是有很大危险性.)删除某目录时也必须具有对父目录的写权限.1.命令格 ...

  3. Laravel 依赖注入原理

    众所周知 Laravel 的文档对于依赖注入只写了如何使用,相信大多数人对于他的实现原理并不太清楚.虽然使用过程中并不需要关心她的原理,但是了解原理让你使用起来更自信.这个帖子就通过一个小 demo ...

  4. indexOf 和 lastIndexOf 使用

    indexOf 的用途是在一个字符串中寻找一个字的位置 lastIndexOf 也是找字 , 它们俩的区别是前者从字符串头开始找,后者是从字符串末端开始找. 一但指定的字被找到,就会返回这个字的当前的 ...

  5. PERL DBI 自动重连问题

    [root@wx03 mojo]# cat relink.pl use Mojolicious::Lite; use JSON qw/encode_json decode_json/; use Enc ...

  6. 2014-08-04 BBS主页页面的设计

    今天是在吾索实习的第19天.这天,开始参照一开始设计的界面原型,真真正正地进行BBS界面的设计.在运用.NET进行界面设计时,发现没有用RP进行界面设计来得容易,很多都要再进行更精细的操作,才能达到原 ...

  7. BNUOJ34990--Justice String (exkmp求最长公共前缀)

    Justice String Given two strings A and B, your task is to find a substring of A called justice strin ...

  8. html基础知识总结2

    下拉列表,文本域,复选框 <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> ...

  9. Apache HttpClient组件封装工具类

    package com.mengyao.spider.utils; import java.util.ArrayList;import java.util.HashMap;import java.ut ...

  10. bui上手体验

    在最近的项目中,接触到了bui这个后台管理框架 主页地址:http://builive.com/ 主页上也有一个后台管理的Demo:http://builive.com/apps/default/ma ...