gpt4 book ai didi

c# - C# 的命名空间范围问题

转载 作者:行者123 更新时间:2023-12-04 16:58:46 25 4
gpt4 key购买 nike

所以我有一个 3 层程序,UI,BLL(业务逻辑层),当然还有 DAL(数据访问层)。 UI 总是与 BLL 对话,BLL 使用 DAL 来检索数据单元,将它们组合成某种格式并将它们返回给 UI。

由于这是我的工作,我想确保始终使用约定(不是每个人都喜欢在任何地方编写自己的风格!)。所以我认为有这样的东西会很好。

using (Bll.MyService service = new Bll.MyService()) {
//My Sweet Code
}

但!!!如果 Bll 位于我的 UI 不在的命名空间中,这将不是一个选项。这是我的意思的一个更详细的例子。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MyApp;

//Entry point
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
//I want to be able to do a using MyApp and access the Bll objects!
Bll.ApiService service = new Bll.ApiService(); //ERROR LINE
}
}
}

//Data access layer
namespace MyApp.DAL
{
class ApiDataAccessor
{
public int MyVar = 1;
}
}

//The bacon letuce layer of course
namespace MyApp.Bll
{
class ApiService
{
public void MyFunction()
{
//todo: make more awesome
}
}
}

如果有人有任何建议,那就太好了!谢谢!

编辑:

添加了 //ERROR LINE代码中的注释,以便使错误明显。我还发现了一个黑客。 using Bll = MyApp.Bll这将强制执行 Bll.ApiService要使用的。我不知道我是否喜欢这个解决方案(因为它很容易搞砸并生气,直到我意识到我没有为命名空间设置别名)。

编辑(再次):

有几种解决方案。
  • using Bll = MyApp.Bll在顶部,然后该命名空间中的所有对象都必须用 Bll.MyObject 引用。这就是我们想要的!
  • 需要完全限定的名称。 MyApp.Bll.MyObject .这是我们不想要的(因为它可能会因大型命名空间而变得冗长)
  • 只需在顶部包含命名空间。 using MyApp.Bll .

  • 总之,我们希望得到 using MyApp以某种方式允许我们引用所有这些命名空间及其对象,例如 Bll.ThisObjectDal.ThatObject但是,如果这是一个需要的解决方案,那么实现这一目标的唯一方法是包含 2 个使用别名的语句。 using Dal = MyApp.Dalusing Bll = MyApp.Bll
    感谢大家的帮助。

    这是解决方案
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using MyApp;
    using Bll = MyApp.Bll;

    //Entry point
    namespace ConsoleApplication2
    {
    class Program
    {
    static void Main(string[] args)
    {
    //I want to be able to do a using MyApp and access the Bll objects!
    Bll.ApiService service = new Bll.ApiService(); // <-- it works.
    }
    }
    }

    //Data access layer
    namespace MyApp.DAL
    {
    class ApiDataAccessor
    {
    public int MyVar = 1;
    }
    }

    //The bacon letuce layer of course
    namespace MyApp.Bll
    {
    class ApiService
    {
    public void MyFunction()
    {
    //todo: make more awesome
    }
    }
    }

    最佳答案

    我认为困惑就在这里:您没有名为 Bll 的命名空间。 .您有一个名为 MyApp.Bll 的命名空间.

    不管有没有using MyApp指令,您需要添加 using MyApp.Bll指令,然后只引用 ApiService直接在您的代码中,或将类完全限定为 MyApp.Bll.ApiService .

    如果您所追求的只是引用 MyApp.Bll 的能力带有符号 Bll 的命名空间,您可以为命名空间设置别名:
    using Bll = MyApp.Bll
    此外,根据对问题的评论和各种答案,值得指出的是 using statement ,它提供了一种方便的方式来声明和清理非托管资源,并且在您的代码中显示为一个块与 using directive 不一样。导入命名空间。

    关于c# - C# 的命名空间范围问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11956675/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com