Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Dynamics are not type safe and do not provide intellisense. You should avoid them in most scenarios. Create a class hierarchy instead</p> <pre><code>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&lt;Photo&gt; Photos { get; set; } } public class Video : Item { public string VideoHash { get; set; } } </code></pre> <p>Now you can create a list of items</p> <pre><code>var list = new List&lt;Item&gt;(); lst.Add(new Article { Id = 1, Text = "test" }); lst.Add(new Video { Id = 1, VideoHash = "34Rgw^2426@62#$%" }); </code></pre> <p>A class serves as template for objects. Derived classes inherit the members from the base class (here <code>Id</code>).</p> <hr> <p><strong>UPDATE</strong></p> <p>A T4 template migth look like this</p> <pre><code>&lt;#@ template inherits="Microsoft.VisualStudio.TextTemplating.VSHost.ModelingTextTransformation" language="C#v3.5" debug="true" hostSpecific="true" #&gt; &lt;#@ output extension=".html" #&gt; &lt;#@ Assembly Name="System.dll" #&gt; &lt;#@ Assembly Name="System.Core.dll" #&gt; &lt;#@ Assembly name="mscorlib.dll" #&gt; &lt;#@ Assembly name="C:\Users\Oli\Documents\Proj\CySoft\StackOverflowTests\StackOverflowTests\bin\Debug\StackOverflowTests.exe" #&gt; &lt;#@ import namespace="System" #&gt; &lt;#@ import namespace="System.Reflection" #&gt; &lt;#@ import namespace="StackOverflowTests.CreateHtmlFromClasses" #&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Example&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;Example&lt;/h1&gt; &lt;table style="Width:100%;"&gt; &lt;# this.AddProperties(new Article { Id = 77, Text = "The quick brown fox." }); #&gt; &lt;/table&gt; &lt;/body&gt; &lt;/html&gt; &lt;#+ private void AddProperties(object obj) { Type type = obj.GetType(); var properties = type.GetProperties();#&gt; &lt;tr&gt; &lt;td&gt; &lt;b&gt;&lt;#= type.Name #&gt;&lt;/b&gt; &lt;/td&gt; &lt;/tr&gt; &lt;#+ foreach (PropertyInfo property in properties) { #&gt; &lt;tr&gt; &lt;td&gt; &lt;#= property.Name #&gt; &lt;/td&gt; &lt;td&gt; &lt;#= property.GetValue(obj, null).ToString() #&gt; &lt;/td&gt; &lt;/tr&gt; &lt;#+ } } #&gt; </code></pre> <p>This example is not a real world example, since it uses the values of an object that of cause would only exist at runtime. You would do only operations based on types. The template engine cannot access types of the current project. Therefore you would have to place it in another project.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload