【发布时间】:2014-04-23 13:19:46
【问题描述】:
我使用 T4 技术创建了简单的类。
<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ output extension=".cs" #>
using System;
<# var properties = new String[]{"P1", "P2", "P3"}; #>
public class MyGeneratedClass {
<#
for(int i = 0; i < 3; i++)
{
#>
private Int32 _<#= properties[i] #> = <#= i #>;
public Int32 <#= properties[i] #>
{
get
{
return _<#= properties[i] #>;
}
}
<#
}
#>
}
然后我创建了一个这样的生成类型的实例
static void Main(String[] args)
{
var template = new Template1();
var text = template.TransformText();
CodeDomProvider codeProvider = new CSharpCodeProvider();
ICodeCompiler compiler = codeProvider.CreateCompiler();
// add compiler parameters
var compilerParams = new CompilerParameters
{
CompilerOptions = "/target:library /optimize",
GenerateExecutable = false,
GenerateInMemory = true,
IncludeDebugInformation = false
};
compilerParams.ReferencedAssemblies.Add("mscorlib.dll");
compilerParams.ReferencedAssemblies.Add("System.dll");
// compile the code
var compilerResults = compiler.CompileAssemblyFromSource(compilerParams, text);
if (compilerResults.Errors.HasErrors)
throw new Exception();
// Создаем экземпляр класса
var instance = compilerResults.CompiledAssembly.CreateInstance("MyGeneratedClass");
if (instance == null)
return;
var TYPE = instance.GetType();
var list = new List<TYPE>();
}
var list = new List<TYPE>();生成编译时错误:
找不到类型或命名空间名称“TYPE”(您是否缺少 using 指令或程序集引用?)
- 有没有办法创建
MyGeneratedClass类类型的泛型列表(或一些泛型集合)? - 有没有更简单的方法来创建
MyGeneratedClass类的实例?
【问题讨论】:
-
如果列表项的类型仅在运行时已知,那么使用通用列表有什么意义?