我写了一个方法来按属性获取属性值:
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;
}
例如:我有属性[Map(Name = "MenuItem, Availability" )]
我调用 GetAttributeValueByNameAttributeAndProperty( codeclass, "Map" , "Name")
在该方法之后获取 CodeAttribute.Value 并返回字符串:Name = "MenuItem, Availability"
删除“Name =”和多余字符并按“,”分割后
但我的高级程序员告诉我,这种方法不灵活,我需要找到一种更方便的方法来获取 CodeAttribute.Value 中的内部数据。
你有什么想法/例子吗?
您可以使用CodeClass.Attributes https://msdn.microsoft.com/en-us/library/envdte.codeclass.attributes.aspxproperty 来获取类的属性。每个属性的类型为CodeAttribute https://msdn.microsoft.com/en-us/library/envdte.codeattribute.aspx并有一个Name https://msdn.microsoft.com/en-us/library/envdte.codeattribute.name.aspx and a Children https://msdn.microsoft.com/en-us/library/envdte.codeattribute.children.aspxproperty 包含属性的参数。每个参数的类型为CodeAttributeArgument https://msdn.microsoft.com/en-us/library/envdte80.codeattributeargument.aspx其中有Name https://msdn.microsoft.com/en-us/library/envdte.codeattribute.name.aspx and Value https://msdn.microsoft.com/en-us/library/envdte80.codeattributeargument.value.aspx特性。
Example
现在您已拥有从中获取属性值所需的所有信息CodeAttribute
。这是一个例子。我装饰过Program
类与[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; }
}
}
这是示例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);
}
}
#>
如果您运行该模板,您将收到"Something"
在输出中。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)