men*_*nsi 10 c# reflection t4 asp.net-mvc-4
我的[Flags]代码中有一些枚举我想要暴露给JavaScript而不需要复制和粘贴.SignalR似乎通过将URL映射到返回由反射生成的JavaScript存根的Action来为其Hub代理做类似的事情.由于代码是在运行时生成的,因此似乎无法将其包含在Bundles中.
作为替代方案,我在设计时实现了一个T4模板来生成一个js文件:
<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ assembly name="EnvDte" #>
<#@ import namespace="EnvDTE" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ output extension=".js" #>
Enums = {
<#
var visualStudio = (Host as IServiceProvider).GetService(typeof(EnvDTE.DTE))
as EnvDTE.DTE;
var project = visualStudio.Solution.FindProjectItem(this.Host.TemplateFile)
.ContainingProject as EnvDTE.Project;
foreach(EnvDTE.ProjectItem item in GetProjectItemsRecursively(project.ProjectItems))
{
if (item.FileCodeModel == null) continue;
foreach(EnvDTE.CodeElement elem in item.FileCodeModel.CodeElements)
{
if (elem.Kind == EnvDTE.vsCMElement.vsCMElementNamespace)
{
foreach (CodeElement innerElement in elem.Children)
{
if (innerElement.Kind == vsCMElement.vsCMElementEnum)
{
CodeEnum enu = (CodeEnum)innerElement;
#> <#= enu.Name #>: {
<#
Dictionary<string, string> values = new Dictionary<string, string>();
foreach (CodeElement child in enu.Members)
{
CodeVariable value = child as CodeVariable;
if (value != null) {
string init = value.InitExpression as string;
int unused;
if (!int.TryParse(init, out unused))
{
foreach (KeyValuePair<string, string> entry in values) {
init = init.Replace(entry.Key, entry.Value);
}
init = "(" + init + ")";
}
values.Add(value.Name, init);
WriteLine("\t\t" + value.Name + ": " + init + ",");
}
}
#>
},
<#
}
}
}
}
}
#>
};
<#+
public List<EnvDTE.ProjectItem> GetProjectItemsRecursively(EnvDTE.ProjectItems items)
{
var ret = new List<EnvDTE.ProjectItem>();
if (items == null) return ret;
foreach(EnvDTE.ProjectItem item in items)
{
ret.Add(item);
ret.AddRange(GetProjectItemsRecursively(item.ProjectItems));
}
return ret;
}
#>
Run Code Online (Sandbox Code Playgroud)
然而,这感觉很脆弱EnvDTE.特别是处理枚举的逻辑如下:
[Flags]
public enum Access
{
None = 0,
Read = 1,
Write = 2,
ReadWrite = Read | Write
}
Run Code Online (Sandbox Code Playgroud)
复合值是一个脏的黑客与字符串替换.上面的T4模板将生成:
Enums = {
Access: {
None: 0,
Read: 1,
Write: 2,
ReadWrite: (1 | 2),
},
};
Run Code Online (Sandbox Code Playgroud)
有没有更清洁的方法来实现这一目标?理想情况下,某种设计时反射生成js文件,因此可用于捆绑.
我喜欢在我的应用程序中使用自定义属性和控制器操作。在开发过程中,我添加一个枚举值并点击“运行”。我浏览到我的控制器操作(仅在调试期间可用的链接)。控制器抓取所有实现自定义 [GenerateJavascriptEnum] 属性的枚举,瞧,我看到一个弹出浏览器窗口,其中包含所有漂亮的 JavaScript。我复制/粘贴并刷新浏览器以获取客户端上的更改。非常舒适,没有什么大惊小怪。
| 归档时间: |
|
| 查看次数: |
1438 次 |
| 最近记录: |