How to get attribute value in CodeAttribute

I wrote a method to get the attribute value by property:

public string GetAttributeValueByNameAttributeAndProperty(CodeClass cc, string nameAttribute, string nameProperty) { var value = ""; foreach(CodeAttribute ca in cc.Attributes) { if(ca.Name.Contains(nameAttribute) && ca.Value.Contains(nameProperty)) { value = ca.Value.Remove(0,ca.Value.IndexOf(nameProperty)); value = value.Replace(" ",""); if(value.Contains(",")) value = value.Remove(ca.Value.IndexOf(",")); } } return value; } 

Example: I have the attribute [Map(Name = "MenuItem, Availability" )]

I call GetAttributeValueByNameAttributeAndProperty (codecs, "Card", "Name") After this method, get CodeAttribute.Value and the returned string: Name = "MenuItem, Availability" After deleting "Name =" and additional characters and "Divide by", "

But my senior programmer told me that this method is not flexible, and I need to find a more convenient way to get the internal data in CodeAttribute.Value.

Do you have any ideas / examples?

+5
source share
1 answer

You can use the CodeClass.Attributes property to get class attributes. Each attribute is of type CodeAttribute and has a Name and Children property containing the attribute arguments. Each argument is of type CodeAttributeArgument , which has a Name and Value .

Example

Now you have all the information you need to get the attribute value from CodeAttribute . Here is an example. I decorated the Program class with the attribute [MySample(Property1 = "Something")]

 using System; namespace ConsoleSample { [MySample(Property1 = "Something")] class Program { static void Main(string[] args) { } } public class MySampleAttribute : Attribute { public string Property1 { get; set; } } } 

And here is a sample of T4 :

 <#@ template debug="true" hostSpecific="true" #> <#@ output extension=".txt" #> <#@ assembly Name="System.Core" #> <#@ assembly name="EnvDte" #> <#@ assembly name="EnvDte80" #> <#@ import namespace="System" #> <#@ import namespace="System.Linq" #> <#@ import namespace="System.Collections.Generic" #> <#@ import namespace="EnvDTE" #> <#@ import namespace="EnvDTE80" #> <# var env = (this.Host as IServiceProvider).GetService(typeof(EnvDTE.DTE)) as EnvDTE.DTE; var project = env.Solution.FindProjectItem(this.Host.TemplateFile).ContainingProject as EnvDTE.Project; var codeClass = project.ProjectItems.Item("Program.cs").FileCodeModel.CodeElements .OfType<CodeNamespace>().ToList()[0] .Members.OfType<CodeClass>().ToList()[0]; var attribute = codeClass.Attributes.Cast<CodeAttribute>() .Where(a=>a.Name=="MySample").FirstOrDefault(); if(attribute!=null) { var property = attribute.Children.OfType<CodeAttributeArgument>() .Where(a=>a.Name=="Property1").FirstOrDefault(); if(property!=null) { var value = property.Value; WriteLine(value); } } #> 

If you run the template, you will get "Something" in the output.

+2
source

All Articles