首页 > 解决方案 > C#创建类实例语法?

问题描述

我对编码很陌生,总是使用“classname instancename=new classname()”来创建实例,但今天我发现以下代码不遵循并且不能使用这种语法。我的问题是第 5 行发生了什么。非常感谢。

private void _InsertIntoBinarySearchTree(ref Element<K> p , K key)
{
    if (p == null)
    {
        p = new Element<K>();//what happens here?
        p.key = key;
    }
    else
    {
        if (p.key.CompareTo(key) > 0)
        {
            _InsertIntoBinarySearchTree(ref p.left, key);
        }
        else if (p.key.CompareTo(key) < 0)
        {
            _InsertIntoBinarySearchTree(ref p.right, key);
        }
        else
        {
            throw new Exception("");
        }
    }
}

标签: c#

解决方案


p如果ref在方法中,那么无论你做什么都会受到它之外的影响;这意味着当您将其分配给new方法参数的调用者时,p也会重新分配。

您说它是Element<K>参数中的一种类型,因此p必须符合该类型。

在方法中,有问题的行,你重新分配p给一个new Element<K> 通孔

p = new Element<K>();//what happens here?

这与p = new Element()您习惯于查看它的方式相同,但由于该Element类型需要泛型类型引用(可能是K或其他任何类型),您还需要使用K传递给该方法的相同类型重新分配它。因为我们不确定K调用时是什么类型。

您不使用的原因var p =...Element<K> p =..因为p已经在参数中声明为该类型。它是一个ref参数,因此您可以按照所述重新分配它。

该方法的调用者可能是这样的,仅作为示例:

Element<string> p = null;
string k = "someKey";
_InsertIntoBinarySearchTree(ref p, k); //Here p goes into the method as ref; the method performs the null check and sets p as new Element<string>()

希望这可以帮助...


推荐阅读