首页 > 解决方案 > Razor 页面命名空间与类库冲突

问题描述

我有一个带有命名空间的剃须刀页面,例如MyApp.Pages.MyClass. 在此页面 cshtml 中,我试图引用类库中的枚举,其命名空间如MyClass.Enums.MyEnum. 我找不到引用此枚举类型的方法,因为它使用完全限定的命名空间(或尝试添加 using 子句)都导致“类型或命名空间不存在”错误,因为它被MyClass.Enums.MyEnum视为相对于当前命名空间MyApp.Pages.MyClass. 有没有一种方法可以在不重命名所涉及的命名空间的情况下引用枚举类型?

标签: c#asp.net-corenamespacesrazor-pages

解决方案


I have a razor page with a namespace like MyApp.Pages.MyClass. Within this page cshtml I am trying to reference an enum in a class library with a namespace like MyClass.Enums.MyEnum.

result in a "Type or namespace does not exist" error

Can reproduce same issue if we name the page model class as MyClass, not MyClassModel.

namespace MyApp
{

    public class MyClass : PageModel

In MyClass.cshtml page and error as below.

enter image description here

To fix it, you can rename your page model class, such as MyClassModel etc.

You can also try another approach to create and use a nested namespace, like below.

namespace MyApp
{
    namespace MyAppNestedNamespace
    {
        public class MyClass : PageModel
        {
            public void OnGet()
            {
                
                //...
            }

            //...
        }
    }

}

The MyClass.cshtml page may look like this:

@page
@model MyAppNestedNamespace.MyClass

@using MyClass.Enums

@{
    ViewData["Title"] = "MyClass";
}

<h1>MyClass</h1>

@*your code here*@

推荐阅读