动态不是类型安全的,也不提供智能感知。在大多数情况下,您应该避免使用它们。改为创建类层次结构
public class Item
{
public int Id { get; set; }
}
public class Article : Item
{
public string Text { get; set; }
}
public class Gallery : Item
{
public string Type { get; set; }
public List<Photo> Photos { get; set; }
}
public class Video : Item
{
public string VideoHash { get; set; }
}
现在您可以创建项目列表
var list = new List<Item>();
lst.Add(new Article { Id = 1, Text = "test" });
lst.Add(new Video { Id = 1, VideoHash = "34Rgw^2426@62#$%" });
类用作对象的模板。派生类从基类(这里Id
)继承成员。
更新
T4 模板可能看起来像这样
<#@ template inherits="Microsoft.VisualStudio.TextTemplating.VSHost.ModelingTextTransformation" language="C#v3.5" debug="true" hostSpecific="true" #>
<#@ output extension=".html" #>
<#@ Assembly Name="System.dll" #>
<#@ Assembly Name="System.Core.dll" #>
<#@ Assembly name="mscorlib.dll" #>
<#@ Assembly name="C:\Users\Oli\Documents\Proj\CySoft\StackOverflowTests\StackOverflowTests\bin\Debug\StackOverflowTests.exe" #>
<#@ import namespace="System" #>
<#@ import namespace="System.Reflection" #>
<#@ import namespace="StackOverflowTests.CreateHtmlFromClasses" #>
<html>
<head>
<title>Example</title>
</head>
<body>
<h1>Example</h1>
<table style="Width:100%;">
<# this.AddProperties(new Article { Id = 77, Text = "The quick brown fox." }); #>
</table>
</body>
</html>
<#+
private void AddProperties(object obj)
{
Type type = obj.GetType();
var properties = type.GetProperties();#>
<tr>
<td>
<b><#= type.Name #></b>
</td>
</tr>
<#+ foreach (PropertyInfo property in properties) {
#> <tr>
<td>
<#= property.Name #>
</td>
<td>
<#= property.GetValue(obj, null).ToString() #>
</td>
</tr>
<#+
}
}
#>
这个例子不是一个真实世界的例子,因为它使用了一个对象的值,因为它只存在于运行时。您只会根据类型进行操作。模板引擎无法访问当前项目的类型。因此,您必须将其放置在另一个项目中。