c# - How get Attribute Value in CodeAttribute -
i wrote method attribute value 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; }
for example: have attribute [map(name = "menuitem, availability" )]
i call getattributevaluebynameattributeandproperty( codeclass, "map" , "name") after method codeattribute.value , return string: name = "menuitem, availability" after remove "name = " , characters , split ","
but senior programmer told me method inflexible , need find more convenient way inner data in codeattribute.value.
do have ideas / examples?
you can use codeclass.attributes
property attributes of class. each attribute of type of codeattribute
, has name
, children
property contains arguments of attribute. each argument of type of codeattributeargument
has name
, value
properties.
example
now have information need attribute value codeattribute
. here example. i've decorated program
class [mysample(property1 = "something")]
attribute
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 sample t4
template:
<#@ 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 iserviceprovider).getservice(typeof(envdte.dte)) envdte.dte; var project = env.solution.findprojectitem(this.host.templatefile).containingproject 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 run template, receive "something"
in output.
Comments
Post a Comment