0

我试图通过传递一些参数(args1,args2)从类 A 调用类 B 的构造函数。我正在使用这样的东西:

public class A
{
       private readonly B _b;
       public A()
       {
         _b=new B(TypeA args1,TypeB args2);
       }

...
}

public class B
{

   public B(TypeA  new_args1,TypeB new_args2)
   {
     ...
   }

...
}

但是从我在调试中看到的 args1 和 args2 具有我想要发送的正确值,new_args1 和 new_args2 不会改变。有没有我必须使用的特定语法来做到这一点?

4

3 回答 3

2

我不确定你为什么将 args 称为 B“new”的构造函数。它们是实例化该特定对象实例的参数。

除了您在参数声明中缺少类型之外,您的代码看起来是正确的。究竟是什么问题。

public B(new_args1,new_args2)

缺少类型,例如

public B(int new_args1, int new_args2)

鉴于上述类型假设

_b=new B(42, 24);

将导致 B 被初始化为

public B(int new_args1, int new_args2)
{
    // new_args1 has the value 42
    // new_args2 has the value 24
}

假设您在 B 中的某处分配这些值,例如

public class B 
{
    public int A1 { get; private set; }
    public int A2 { get; private set; }
    public B(int new_args1, int new_args2)
    {
        // new_args1 has the value 42
        A1 = new_args1;
        // new_args2 has the value 24
        A2 = new_args2;
    }
}

然后

_b.A1 

将具有值 42,并且

_b.A2

将具有值 24

初始化_b之后。

于 2012-07-30T14:39:30.637 回答
1

首先让我们修复语法:

public class A
{
    private readonly B _b;
    public A(TypeA args1, TypeB args2)
    {
        _b = new B(args1, args2);
    }

}

public class B
{
    public B(TypeA new_args1, TypeB new_args2)
    {

    }

}

请注意,参数类型必须完全匹配,否则可能会调用具有匹配签名的另一个构造函数。假设B在这种情况下您有两个构造函数,第一个被调用,第二个没有:

public class B
{
    public B(TypeA new_args1, TypeB new_args2)
    {

    }

    public B(TypeA new_args1, TypeC new_args2)
    {

    }

}

还有一点:在这种情况下,我会使用 DI(依赖注入)。在构造函数中进行构造是一个缺陷,除非构造的对象是诸如 等的原子数据List结构Dictionary

public class M
{
    public void Main(TypeA new_args1, TypeB new_args2)
    {
        var b = new B(new_args1, new_args2);
        var a = new A(b);
    }
}


public class A
{
    private readonly B _b;
    public A(B b)
    {
        _b = _b;
    }

}

public class B
{
    public B(TypeA new_args1, TypeB new_args2)
    {

    }
}
于 2012-07-30T14:52:47.100 回答
0

那么我在你的代码中看到的错误是你应该用括号声明你的 A 构造函数,即 A() 并检查它是否有效。除此之外,您的代码看起来绝对正确。

于 2012-07-30T14:45:33.910 回答