![](/img/trans.png)
[英]Tool to measure the time taken for a code to run in visual studio 2010 ide
[英]How to create a custom tool to generate code in Visual Studio 2010?
我只想生成一個包含來自Database表的屬性的類 。
如果我有一個如下所示的數據庫表:
+-------------------+
| Id | Name |
+----+--------------+
| 1 + foo |
| 2 + hello.world |
| 3 + null |
+-------------------+
我想自動生成一class
是將如下所示:
class MyTable {
public static int Foo = 1;
public static int HelloWorld = 1;
// null was omitted for Id = 3
}
您可以使用T4轉換來完成工作。 使用“添加新項目”和“文本模板”。
T4語言是一種使用C#代碼生成C#代碼的方法。 大多數文本都直接解析為輸出文件,新代碼可以寫在<#
和#>
標記內。 該文件以包裝的import和using語句開頭,因此一個非常簡單的模板可能是這樣的:
<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ import namespace="System.Data" #>
<#@ import namespace="System.Data.SqlClient" #>
<#@ assembly name="System.Data" #>
namespace Some.Namespace
{
public class TestClass
{
<#
using(var cnn = new SqlConnection(@"server=.\sqlexpress;Integrated Security=SSPI;Database=ApplicationManagement"))
{
cnn.Open();
var cmd = new SqlCommand("SELECT TextKey, TextValue FROM TblBrandingKeyValues WHERE BrandingIdentifier = 'Default'", cnn);
var reader = cmd.ExecuteReader();
while (reader.Read())
{
var defaultText = reader.GetString(1);
var name = reader.GetString(0);
#>
public string <#= name #>
{
get { return "<#= defaultText #>"; }
}
<#
}
}
#>
}
}
} <#@ output extension =“。cs”#>
此模板將創建一個類TestClass
, TestClass
包含從數據庫表TblBrandingKeyValues
檢索的一組只讀屬性。
我會推薦這些T4教程 。
如果要創建自己的自定義工具,最好查看System.CodeDom
命名空間,其中包含生成代碼所需的全部內容。 當然,您必須編寫生成類的算法。
更多信息在以下鏈接:
http://msdn.microsoft.com/en-us/library/ms404245.aspx
請記住,.NET已經提供了許多完成相同工作的“內置”工具/命名空間(例如使用實體框架)
使用T4模板 。 我通過這種方式生成了很多類。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.