我使用 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
class?
- 有没有更简单的方法来创建实例
MyGeneratedClass
class?
Type genericListType = typeof(List<>);
Type[] typeArgs = new[] { instance.GetType() };
var generic = genericListType.MakeGenericType(typeArgs);
System.Collections.IList list = (System.Collections.IList)Activator.CreateInstance(generic);
foreach (dynamic item in list)
{
//whatever
}
希望我对你说得对..
编辑一些更有用的东西,
这种方法对于数组列表只是如果您尝试添加与特定运行时类型不同的内容,则运行时会出现异常。尽管数组列表在添加“错误”项目的情况下不会引发异常,相反,如果您使用这些项目,则会出现或不会出现异常。我确实(即使我在编译时不知道类型)尝试使用具体的泛型而不是开放的数组列表,因为异常是在正确的代码行引发的(恕我直言)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)