Reputation: 47
I'm reading an opensource c# project, and in some basic classes, there are a lot of custom attributes, like the following:
[Parameter("aaa", typeof(int), "this is aaa")]
[Parameter("bbb", typeof(bool), "this is bbb")]
[Serializable]
public class Number : DataElement
{
...
}
Now I need to understand these custom Attributes but there is no documentation. So I need to find which function do things based on these custom Attributes.And from reading these function,I can get the meaning.
Is there a thorough way to locate the function in the project,the function will do sth based on certain custom Attributes?
Upvotes: 2
Views: 396
Reputation: 166
Attribute is nothing but an information. This information can be attached to your method, class, namespace, assembly etc.
You will be very much clear after visiting the following URL.
Upvotes: 2
Reputation: 56859
Attributes are designed to add metadata to a code element (such as a class). This metadata can be read by any piece of code via .NET Reflection as in this answer.
Some Attributes are read by the compiler (such as [Serializable]
), some are read by specific .NET frameworks such as ASP.NET MVC (such as [Route]
, which only works if you call RouteTable.Routes.MapMvcAttributeRoutes()
), and you can make custom Attributes for your own purposes.
In general, I would recommend reading the documentation about the specific Attribute you are interested in finding what it does. If you need to view the code that uses it, you can use a tool such as .NET Reflector or ILSpy (assuming you know which .NET assembly that code is in - again via documentation).
It might help if you would explain why you need this, as there doesn't seem to be much benefit in knowing what function looks up a particular Attribute (unless it is your own custom Attribute), as long as you know what it is for.
Upvotes: 2
Reputation: 3974
I would suggest you write a snippet of code somewhere, then output to file, console or debugger.
First You need to loop through every method on every type, then check whether it has your attribute you are looking for. I presume it's ParameterAttribute
.
For example:
var methods = assembly.GetTypes()
.SelectMany(t => t.GetMethods())
.Where(m => m.GetCustomAttributes(typeof(ParameterAttribute), false).Length > 0)
.ToArray();
foreach (var assemblyMethod in methods)
{
Console.WriteLine(assemblyMethod.Name);
// or do other stuff here
}
For more info on getting custom attributes, read Here. Also, this is part of reflection which you can learn more about Here
Upvotes: 1