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

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

问题描述

在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){ ... }

我想导出的控制传递给函数 例如下面的code

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);

生成转换错误

Generates a conversion error

好吧,我可以接受,但下面混淆了我(可能是因为我用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 参数是的确切的类型(无多态性)和该类型的引用必须是可分配的。这就是为什么你必须创建通过显式的转换在单独的步骤参照,以便该方法具有某一变量可以被分配正确类型的引用。

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.

有关此主题的更多信息,请参阅<一href="http://blogs.msdn.com/ericlippert/archive/2009/09/21/why-do-ref-and-out-parameters-not-allow-type-variation.aspx">Why做ref和out参数不允许类型变化由埃里克利珀的:

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

如果你有一个方法,需要一个X   那么你必须通过一个前pression   X型或东西转换为X.   再说了,一个类型的前pression派生   从十,但如果你有一个方法,   需要一个参考X,你必须通过一个   REF到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天全站免登陆