如何获取CodeAttribute中的属性值

How get Attribute Value in CodeAttribute

我写了一个获取属性值的方法 属性:

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" )]

我调用 GetAttributeValueByNameAttributeAnd属性( codeclass, "Map" , "Name") 在该方法之后得到 CodeAttribute.Value 和 return 字符串: Name = "MenuItem, Availability" 在我删除 "Name = " 和多余的字符并按 ","

拆分后

但是我的高级程序员告诉我这种方法不灵活,我需要找到一种更方便的方法来获取CodeAttribute.Value中的内部数据。

你有什么想法/例子吗?

您可以使用 CodeClass.Attributes property to get attributes of a class. Each attribute is of type of CodeAttribute and has a Name and a Children property which contains arguments of the attribute. Each argument is of type of CodeAttributeArgument which has Name and Value 个属性。

例子

现在您拥有从 CodeAttribute 获取属性值所需的所有信息。这是一个例子。我用 [MySample(Property1 = "Something")] 属性

装饰 Program class
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"