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

前端 未结 3 591
我寻月下人不归
我寻月下人不归 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: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?

提交回复
热议问题