Getting the CodeClass from argument inside CodeAttribute?
I am working on some T4 code generation, for this I need the CodeClass of the type that is passed inside the constructor of BarAttribute.
class Baz { }
class Bar : Attribute { public Bar (Type type) { } }
[Bar(typeof(Baz))]
public class Foo
{
}
This is what I have so far inside my T4 Template, I just give the CodeAttribute '[Bar(typeof(Baz))]' to the function:
private CodeClass GetType(CodeElement codeElement)
{
CodeAttribute attribute = (CodeAttribute)codeElement;
if (attribute.Name == "Bar")
{
foreach (CodeElement child in attribute.Children)
{
EnvDTE80.CodeAttributeArgument attributeArg = (EnvDTE80.CodeAttributeArgument)child;
WriteLine(attributeArg.Value);
}
}
return null;
}
The function now will just write: typeof(Baz), how can I get the CodeClass of Baz (which can be inside another assembly w开发者_C百科ithin the solution) without iterating thru all Projects, ProjectItems, CodeElements, etc?
As per William's reply, you are limited to the design-time information, which will be the unparsed text passed to the attribute. If you are interested in finding the CodeClass referenced in the typeof keyword without resorting to recursion, you can use the VisualStudioAutomationHelper
class found in tangible's T4 Editor template gallery. You use it like this:
var project = VisualStudioHelper.CurrentProject;
var allClasses = VisualStudioHelper.GetAllCodeElementsOfType(project.CodeModel.CodeElements, EnvDTE.vsCMElement.vsCMElementClass, false);
allClasses.Cast<EnvDTE.CodeClass>().Single(x => x.Name == searchedClassName);
精彩评论