在方法中传递对派生对象的引用时出错 [英] error when passing a reference to a derived object in a method

查看:24
本文介绍了在方法中传递对派生对象的引用时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In c# I am trying to implement a method which I can use to bind data to any control I pass to it (provided of course the control is derived from a databoundcontrol object)

给定方法

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

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

I get an error when trying to pass derived control to the function
for example the following code

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

产生转换错误

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

Ok I can accept that, but the following confuses me (probably because I am used to c++ not c#)

CTLBindData(ref (DataBoundControl)lister);

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

in this case I get the error "A ref or out argument must be an assignable variable"

澄清一个 Dropdownlist 继承自一个从 DataBoundControl 继承的列表控件

For clarification A Dropdownlist inherits from a list control which inherits from a DataBoundControl

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

This makes no sense to me I should be able to pass in any object that has been derived from a databound control. It seems that the explicit typecast is causing the problem.

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

Any clues as to what I am doing wrong?

DC

推荐答案

在调用方法之前先执行转换,如下所示:

Do the cast prior to calling the method like this:

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

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

C# requires that any ref parameters be of the exact type (no polymorphism) and the reference of that type must be assignable. This is why you must create the reference via explicit cast in a separate step so the method has a reference of the correct type to which a value can be assigned.

有关此主题的更多信息,请参阅 为什么 ref 和 out 参数不允许类型变化? 作者 Eric Lippert:

For more information about this topic please see Why do ref and out parameters not allow type variation? by Eric Lippert:

如果您有一个带有X"的方法那么你必须传递一个表达式键入 X 或可转换为 X 的东西.比如说,一个派生类型的表达式从 X. 但如果你有一个方法需要一个ref X",你必须通过一个引用 X 类型的变量,句点.这是为什么?为什么不允许类型变化,就像我们处理非引用调用一样?

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?

这篇关于在方法中传递对派生对象的引用时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆