c# - 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("");
}
}
}
解决方案
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>()
希望这可以帮助...
推荐阅读
- python - Django rest-framework 通过与外键连接的其他模型的名称过滤模型
- d3.js - d3jsv4 时间线图,在擦洗期间带有垂直月轴
- java - 在 TestNG 上更改 JUnit,NullPointerException
- python - 安装 Python Python 3.7 + Tensorflow 2.0 + Jupyter Notebook 2020 并面临问题
- android - 如果 BLE 服务器在 Android 6 上运行,则 BLE 状态 GATT_CONN_TERMINATE_PEER_USER
- shell - AppleScript 到 Shell 脚本
- javascript - 重定向空提取请求
- python - 在python中绘制球体
- javascript - Firebase身份验证的onAuthStateChanged中的重定向加载页面无穷无尽
- html - 如何隐藏水平滚动