【问题标题】:Initialize values in Interface在接口中初始化值
【发布时间】:2014-07-31 14:32:37
【问题描述】:

我有一个公开接口的 dll,如下所示:

public Interface IClientGroup
{
IQueryable ClientsGroup {get;}
void Activate(ClientGroup clientgroup);
//many other members and functions
}

在我的控制器类中,它像这样在构造函数中传递:

public ControllerClass(IClientGroup clientgroup)
{
  var _clientgroup = clientgroup
}

//later _clientgroup used to access everything in Interface

现在,当我调试时,我看到它在传递给构造函数时,值已经初始化,所以我假设我可以简单地在任何函数中传递 IClientgroup clientgroup 并且它已经初​​始化但它为空,每次如果我在使用之前声明它并说it is type but used as variable 如果我直接传递给在构造函数中完成的函数。

public UseValues(IclientGroup clientgroup)
{
  //error: IClientGroup is type but used as variable
}

如何使用已初始化值的客户端组?我无法从 dll 中看到确切的实现。

【问题讨论】:

  • var _clientgroup = clientgroup 在 ctor 内部初始化本地变量,您将无法在课堂的其他地方重用它。为此使用私有字段或属性
  • 这几乎是 OOP 101。在深入研究之前,您可能需要花一些时间退后一步,学习一些基本的面向对象编程。

标签: c# asp.net asp.net-mvc asp.net-mvc-3 asp.net-mvc-4


【解决方案1】:
public ControllerClass(IClientGroup clientgroup)
{
  var _clientgroup = clientgroup
}

以上代码将clientgroup 参数存储到局部变量中,而不是实例字段中。您需要将其存储在实例字段中以便以后使用。

class ControllerClass
{
    private IClientGroup _clientgroup;
    public ControllerClass(IClientGroup clientgroup)
    {
       if(clientgroup == null)
       {
           //Don't allow null values
           throw new ArgumentNullException("clientgroup");
       }
       this._clientgroup = clientgroup
    }

    void SomeMethod()
    {
        //Use this._clientgroup here
    }
}

除了问题你真的需要beginner tutorial

【讨论】:

  • 我知道这个问题是微不足道的。很抱歉再次询问,但客户端组将用于其他一些类(实际上是测试类),它似乎没有用那里的值初始化。我不能在那里使用this._clientGroup
  • 不,这指向当前实例(这里是ControllerClass)你不能在其他类中访问它。如果需要使用,则创建IClientGroup 类型的公共属性并使用controllerClassInstance.ClientGroupProperty。请再次了解基础知识..
猜你喜欢
  • 1970-01-01
  • 2018-02-05
  • 1970-01-01
  • 1970-01-01
  • 2014-07-28
  • 1970-01-01
  • 2020-02-08
  • 1970-01-01
  • 2022-12-04
相关资源
最近更新 更多