剃须刀引擎模板中的类 [英] Classes in razor engine template
问题描述
是否可以在模板中创建类?像...
Is it possible to create classes within a template? Something like...
@{
public class MyClass {
public MyClass() {
Three = new List<string>();
}
public string One { get; set; }
public int Two { get; set; }
public List<string> Three { get; set; }
}
}
当前,我得到无法编译模板.请查看错误列表以获取详细信息."当我尝试这样做时.我想获取XML内容,并使用XmlSerializer在模板中创建MyClass的实例.我不能先进行反序列化并将其推入模型中,因为类可能会因模板而异.
Currently I get "Unable to compile template. Check the Errors list for details." when I try to do this. I would like to take XML content and use XmlSerializer to create an instance of MyClass within the template. I can't do the deserialization before hand and shove it into the model because the classes could vary depending on the template.
推荐答案
我将发布 CodePlex讨论在这里:
我不确定目前是否可行.当您使用代码块(@ {})时,实际上是在方法中编写代码,例如您上面的代码将执行以下操作:
I'm not sure that is currently possible. When you use codeblocks (@{ }), you're actually writing code within a method, e.g. your above code would do something like:
public void Execute()
{
this.Clear();
public class MyClass {
public MyClass() {
Three = new List<string>();
}
public string One { get; set; }
public int Two { get; set; }
public List<string> Three { get; set;}
}
}
...这当然不是有效的C#.您将面临的另一个问题是,要使用xml序列化/反序列化,必须知道类型,但是如果您在模板本身中定义类型,那么首先如何反序列化呢?
...which of course, is not valid C#. The other problem you will face, is that to use xml serialisation/deserialisation, the type must be known, but if you are defining your type within the template itself, how could you deserialise it in the first place?
您可能所能做的就是使用自定义基本模板:
What you could do, is use a custom base template:
public class CustomTemplateBase<T> : TemplateBase<T>
{
public dynamic Instance { get; set; }
public dynamic CreateInstance(string typeName)
{
Type type = Type.GetType(typeName);
// You'd to your deserialisation here, I'm going to
// just cheat and return a new instance.
return Activator.CreateInstance(type);
}
}
使用动态属性和动态返回类型,我们定义了一个方法,该方法使我们可以创建一个实例(通过激活或反序列化等)并调用该实例上的成员访问权限.要在模板中使用它,您可以执行以下操作:
Using a dynamic property and dynamic return type, we've defined a method that will let us create an instance (through activation or deserialisation, etc.) and call member access on it. To use that in a template, you could then do:
@{
Instance = CreateInstance("ConsoleApplication1.MyClass, ConsoleApplication1");
Instance.One = "Hello World";
}
<h1>@Instance.One</h1>
其中"MyClass"是在应用程序中的某个位置定义的.重要的是,我正在为每个模板创建一个实例.
Where "MyClass" is a defined somewhere in my application. The important thing is, I'm creating an instance per template.
这篇关于剃须刀引擎模板中的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!