我想知道是否可以将C#代码片段保存到文本文件(或任何输入流),然后动态执行它们?假设提供给我的内容可以在任何Main()块中编译好,是否可以编译和/或执行此代码?出于性能原因,我更愿意编译它.
至少,我可以定义一个他们需要实现的接口,然后他们将提供一个实现该接口的代码"section".
如何可以解析C#风格格式的泛型类型名称List<int>或者Dictionary<string,int>甚至更复杂Dictionary<string,Dictionary<System.String,int[]>>.假设这些名称是字符串,实际上可能不代表现有类型.它应该很容易解析BogusClass<A,B,Vector<C>>.为了清楚起见,我对解析格式的.NET内部类型名称并不感兴趣List`1[[System.Int32]],而是对源代码中出现的实际C#类型名称感兴趣,使用点表示法有或没有名称空间限定符.
正则表达式是因为这些是嵌套结构.我想也许System.CodeDom.CodeTypeReference构造函数会为我解析它,因为它有string BaseType和CodeTypeReferenceCollection TypeArguments成员,但那些显然需要手动设置.
CodeTypeReference是我需要的一种结构:
class TypeNameStructure
{
public string Name;
public TypeNameStructure[] GenericTypeArguments;
public bool IsGenericType{get;}
public bool IsArray{get;} //would be nice to detect this as well
public TypeNameStructure( string friendlyCSharpName )
{
//Parse friendlyCSharpName into name and generic type arguments recursively
}
}
Run Code Online (Sandbox Code Playgroud)
框架中是否有任何现有的类来实现这种类型名称解析?如果没有,我将如何解析这个?
比方说我有:
@{
var str= "DateTime.Now";
}
Run Code Online (Sandbox Code Playgroud)
我想将此字符串作为ac#代码处理
@Html.Raw(App.ProcessAsCode(str));
Run Code Online (Sandbox Code Playgroud)
输出应该是当前日期时间.