c# - 在方法中传递对派生对象的引用时出错

标签 c# .net inheritance reference

在 c# 中,我正在尝试实现一种方法,我可以使用该方法将数据绑定(bind)到我传递给它的任何控件(当然前提是该控件派生自 databoundcontrol 对象)

给定方法

 public void CTLBindData(ref DataBoundControl ctl){ ... }

尝试将派生控制传递给函数时出现错误
例如下面的代码

DropDownList lister = new DropDownList();  
CTLBindData(ref lister);

产生转换错误

好吧,我可以接受,但下面的内容让我感到困惑(可能是因为我习惯于 c++ 而不是 c#)

CTLBindData(ref (DataBoundControl)lister);

在这种情况下我得到了错误 “ref 或 out 参数必须是可分配的变量”

为了澄清,Dropdownlist 继承自列表控件,列表控件继承自 DataBoundControl

这对我来说毫无意义,我应该能够传入从数据绑定(bind)控件派生的任何对象。似乎是显式类型转换导致了问题。

关于我做错了什么的任何线索?

直流

最佳答案

在像这样调用方法之前进行转换:

DataBoundControl countrol = (DataBoundControl)lister;
CTLBindData(ref control);

C# 要求任何 ref 参数都是 exact 类型(无多态性)并且该类型的引用必须是可分配的。这就是为什么您必须在单独的步骤中通过显式强制转换创建引用,以便该方法具有可以为其分配值的正确类型的引用。

有关此主题的更多信息,请参阅 Why do ref and out parameters not allow type variation?埃里克·利珀特:

If you have a method that takes an "X" then you have to pass an expression of type X or something convertible to X. Say, an expression of a type derived from X. But if you have a method that takes a "ref X", you have to pass a ref to a variable of type X, period. Why is that? Why not allow the type to vary, as we do with non-ref calls?

关于c# - 在方法中传递对派生对象的引用时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1665339/

相关文章:

c# - 增加检索的记录数会成倍增加 linq 查询持续时间

c# - 如何将 DynamoDB 属性设置为空列表?

c# - SqlDataReader 与数据集

c# - LoadLibrary 并定义对 C DLL 的回调(函数指针)

sql - 从父表中选择一行时显示子表名称

delphi - 从专门的泛型类型派生

javascript - 当 JavaScript 中的类没有默认构造函数时,如何扩展它?

c# - 在声明中存储字符串列表 (System.Security.Claims)

c# - MySQL 本地/在线服务器不会响应 C#/.NET

.net - 为什么我得到 OutOfMemory Exceptions 尽管可以释放内存?