在 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/