开发者

Overloaded VB.NET extension method in class library

开发者 https://www.devze.com 2023-01-08 14:32 出处:网络
It seems that my library of extension methods that was written in VB.NET has problems. I have 2 overloaded extension methods Crop().

It seems that my library of extension methods that was written in VB.NET has problems.

I have 2 overloaded extension methods Crop().

When i reference the lib from a VB.NET project i see them. If reference it from a C# project i can't see t开发者_如何学Pythonhem.

What the hell is going on?


It works like this:

  • In C#, when you call a method with an out or ref parameter, the compiler requires you to repeat the out or ref keyword on the calling argument. This is because it does matter to the language whether the variable is already initialised or not.
  • In VB.NET, when you call a method with a ByRef parameter, the compiler does not require you to repeat ByRef on the calling argument, it just sorts it out for you. This is because it does not matter to the language whether the variable is already initialised or not.

Therefore, VB.NET can easily resolve an extension method using ByRef, because there is only one possible way in which it can be called. However, C# does not know what to do because there is no syntax for telling it whether to call the method using out or ref.

All you can do is:

  • Re-write your extension methods to use a ByVal parameter wherever possible.
  • If that is not possible, then you are stuck with calling them from C# like normal methods.


Without seeing the code, my guess is that you're missing a using statement in your C# .cs file.

//other usings...

//Extension using statement...
using MyAssembly.Extensions;

class Program {
  static void Main() {
    //some code
    String myString = "blah";

    //call the extension method now
    String newString = myString.MyExtensionMethod();
  }
}

But this is just a guess without seeing your code.

Hope this helps!!


My methods were using byref arguments. I changed it to byval and it worked.

It's very weird apparently. In VB projects its ok but in C# not. Apparently C# does not support extension methods with byref or it is a bug.

0

精彩评论

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