error when passing a reference to a derived object in a method

前端 未结 3 609
我寻月下人不归
我寻月下人不归 2020-12-07 02:59

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)

相关标签:
3条回答
  • 2020-12-07 03:32

    Andrew Hare answered very well.

    Your object must need something inside to use REF or OUT. For example: could be null.

    DropDownList lister = new DropDownList();
    lister = null;   
    CTLBindData(ref lister);
    
    0 讨论(0)
  • 2020-12-07 03:45

    Andrew Hare is correct, but in this case, you may not even want to be using the ref. Objects in C# are already passed by reference*. (As opposed to value types, which are not passed by reference unless you use the ref keyword.) There are very few cases that I can think of where you'd actually need to pass a reference type in that way. Without the ref, your original code should work just fine.

    **Not really, but it's easier to understand that way if you come from a non-C# background. The reference is actually passed by value. There is an excellent article on the exactly how this all works.*

    0 讨论(0)
  • 2020-12-07 03:51

    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?

    0 讨论(0)
提交回复
热议问题