开发者

Convert vb.net static method call on object

I am having more problems with my converting of vb.net to c#.net.

I have some files in vb.net that have "Option Strict Off" to allow for bad programming. When I convert to c# I use "dynamic" until I come back and fix problems, and this works in all cases

But now I have this code:

Public Class ContractResults
   'Big class definition
   Public Shared Sub CleanCache()
       'Code here
   End Sub
End Class

And in a file with Option Strict Off:

Public Sub VerifyResults(result as Object)
   'Here, result is normally ContractResults
   'first it check for that then call this:
   result.CleanCache()
End Sub

In c# I use "dynamic", but a runtime error pops up when I call "static" method with dynamic reference. In vb.net, I can called "shared" sub from instance, but in c# this is not allowed

Exception: "Microsoft.CSharp.RuntimeBinder.RuntimeBinderException" "Member 'ContractTypes.ContractResults.CleanCache()' cannot be accessed with an instance reference; qualify it with a type name instead"

It seems I must convert code to use ac开发者_运维百科tual type, but then this means much rewriting of more parts. Is anyone able to show another way?

I want to make sure you do not think I can use

(result as ContractResults).CleanCache();

Because all types that may be passed in have "CleanCache()" method, but do not inherits from anything the same other than "Object". There are many types (30!) that have this "static" method and so that is why it uses Option Strict Off


You could use reflection:

result.GetType().InvokeMember("CleanCache", BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy, null, null, new object[0]);

(untested)


As the error suggests, you have to call a static method from the class, not an instance:

ContractResults.CleanCache();

You could put your 30 types into a switch statement, but this would be ugly.


I'm sorry to say this, but the original decision to turn Option Strict Off was a bad one. Somehow I doubt that the code that was originally written does what you think it's doing anyway.

It's time to just go ahead and fix that problem.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜