C#扩展方法检查属性 [英] C# Extension method for checking attributes

查看:117
本文介绍了C#扩展方法检查属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好
很抱歉,如果这是一个愚蠢noob问题,请善待我,我想了解...

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

我要测试反对的东西像模型和控制器属性的方法。主要是为了确保他们有正确的attrbute即必需。但我也用这个为扩展方法和Lambda表达式的试验。

I want to test against the attribute methods of things like models and controllers. Mostly to make sure they have the right attrbute ie Required. But i'm also using this as an experiment with extension methods and Lambdas.

我想是一种方法,它的形式实现的时候看起来有些东西一样

What I'd like is a method that when implimented looks some thing like

Controller controller = new Controller();
controller.MethodName(params).HasAttribute<AttributeName>();



Iveused扩展方法一点,但没有到这个程度。我敢肯定这应该是足够简单。这样做,但不能似乎得到我的仿制药等正确

Iveused extension methods a little but not to this degree.. I'm sure this should be simple enough to do but cant seem to get my generics etc correct.

推荐答案

也许你正在寻找这样的:

Perhaps you are looking for this:

Controller controller = new Controller();
bool ok = controller.GetMethod(c => c.MethodName(null, null))
    .HasAttribute<AttributeName>();

什么是关于这样写的好处在于,你已经充分编译时的支持。所有其他解决方案迄今使用字符串来定义的方法。

What's nice about writing it like this is that you have fully compile time support. All other solutions thus far use string literals to define the methods.

下面是的 GetMethod 和实施 HasAttribute< T> 扩展方法:

Here are the implementations of the GetMethod and HasAttribute<T> extension methods:

public static MethodInfo GetMethod<T>(this T instance,
    Expression<Func<T, object>> methodSelector)
{
    // Note: this is a bit simplistic implementation. It will
    // not work for all expressions.
    return ((MethodCallExpression)methodSelector.Body).Method;
}

public static MethodInfo GetMethod<T>(this T instance,
    Expression<Action<T>> methodSelector)
{
    return ((MethodCallExpression)methodSelector.Body).Method;
}

public static bool HasAttribute<TAttribute>(
    this MemberInfo member) 
    where TAttribute : Attribute
{
    return GetAttributes<TAttribute>(member).Length > 0;
}

public static TAttribute[] GetAttributes<TAttribute>(
    this MemberInfo member) 
    where TAttribute : Attribute
{
    var attributes = 
        member.GetCustomAttributes(typeof(TAttribute), true);

    return (TAttribute[])attributes;
}

这篇关于C#扩展方法检查属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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