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 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 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.
C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...
What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.
In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.
Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With