Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
127 views
in Technique[技术] by (71.8m points)

c# - error when passing a reference to a derived object in a method

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)

given the method

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

Generates a conversion error

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

CTLBindData(ref (DataBoundControl)lister);

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Do the cast prior to calling the method like this:

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

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.

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

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...