开发者

Method with Object argument won't accept anything other than an Object

开发者 https://www.devze.com 2022-12-08 00:38 出处:网络
We have a VB.net function with the following signature in class InitializerFactory: Public Shared Function Create(ByRef ui As Object) As IModeInitializer

We have a VB.net function with the following signature in class InitializerFactory:

Public Shared Function Create(ByRef ui As Object) As IModeInitializer

I'm atte开发者_JS百科mpting to test this function by passing in a mock of ui (using Rhino Mocks):

MainForm ui = mocks.StrictMock<MainForm>();
IModeInitializer item = InitializerFactory.Create(ref ui);

When attempting to pass ui as a parameter, I get the following errors:

  • The best overloaded method match for 'InitializerFactory.Create(ref object)' has some invalid arguments
  • Argument '1': cannot convert from 'ref MainForm' to 'ref object'

Ideally, the solution would be to extract an interface on UI (or its class, MainForm) but that's not doable by any means - it's an extremely bloated class.

I also can't declare ui as an Object, or else I can't mock the methods inside of it since the methods don't belong to an Object type.

My question is -- what am I doing wrong?


This is just because of the ref parameter syntax. The problem is that the function has to be able to set ANY type of object, since it's a by ref parameter. You can't just pass it a reference to a MainForm, which is what you're attempting.

Unfortunately, this is a pretty difficult API to work with.

You can handle this by assigning your instance to an object first:

MainForm ui = mocks.StrictMock<MainForm>();
object uiObj = ui;
IModeInitializer item = InitializerFactory.Create(ref uiObj);
if (uiObj != ui) { 
    // Handle the case where the reference changed!
    ui = uiObj as MainForm; // May be null, if it's no longer a "MainForm"
}

If you want to fully understand this, you can read up on Covariance and Contravariance.

0

精彩评论

暂无评论...
验证码 换一张
取 消