加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 01:32:58 所属栏目:百科 来源:网络整理
导读:在c#中,我试图实现一个方法,我可以使用它将数据绑定到我传递给它的任何控件(当然,控件是从数据绑定控件对象派生的) 给定方法 public void CTLBindData(ref DataBoundControl ctl){ ... } 尝试将派生控件传递给函数时出错 例如以下代码 DropDownList lister =
在c#中,我试图实现一个方法,我可以使用它将数据绑定到我传递给它的任何控件(当然,控件是从数据绑定控件对象派生的)

给定方法

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

尝试将派生控件传递给函数时出错
例如以下代码

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

生成转换错误

好的我可以接受,但以下让我困惑(可能是因为我习惯了c而不是c#)

CTLBindData(ref (DataBoundControl)lister);

在这种情况下,我得到错误
“ref或out参数必须是可赋值变量”

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

这对我来说没有任何意义我应该能够传递任何从数据绑定控件派生的对象.似乎显式的类型转换导致了这个问题.

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

DC

解决方法

在调用方法之前执行强制转换:

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

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

有关该主题的更多信息,请参阅Eric Lippert的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?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读