c# - Razor 引擎模板中的类

标签 c# razor

是否可以在模板中创建类?像...

@{
    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 的实例。我无法事先进行反序列化并将其插入模型,因为类可能因模板而异。

最佳答案

是的,这是完全可能的。使用 @functions 关键字:

@functions {
    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# - Razor 引擎模板中的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5129663/

相关文章:

c# - WebAPI ApiExplorer 帮助页面参数附加信息

c# - 将 json 对象引用到字符串时出现 RuntimeBinderException

c# - 如何查找 Span<T> 是否包含相同顺序的其他 Span<T>

asp.net-mvc - 内联如果在Razor View 中

asp.net-core - Razor 页面中的流利验证

c# - 用于在 XAML 中绑定(bind) TimeSpan 的 StringFormat 不起作用

c# - 如何访问 .csx 脚本中的命令行参数?

c# - 创建 View 中可用的自定义助手

razor - Umbraco、 Razor 和图片库

asp.net-mvc-3 - 用于ASP.NET MVC的Razor View Engine的源代码在哪里?