简体   繁体   中英

C# implicit conversion without cast

I am converting VB.net code to C# and I am facing a problem. With VB.net, I have functions that use OBJECT parameters. These parameters are usually of 2 differents types which have the same methods that I need. Example:

Public Sub test(param1 as Object)
    param1.show()
End Sub

With C#, I do the same kind of function, but the compiler won't accept it.

public void test(object param1)
{
    param1.show(); // Error on .show (not found)
}

I should probably cast the parameter in some way, but I need to send different types to the function. Is it possible?

This is why interfaces exist.

public interface IShowable {
    void show();
}

class YourClassFromAbove {
    public void test(IShowable param1)
    {
        param1.show();
    }
}

Any type passed in must implement the IShowable contract which solves the problem.

If you have Option Strict Off set using Object is the equivalent to using dynamic in C#

public void test(dynamic param1)
{
    param1.show();
}

However, I really, REALLY, recommend you do not do that. dynamic was invented to help with writing late bound code (that is also the job Object served in VB6 when this feature was introduced), you really should use a class with a interface to get the strong type info for your code.

Or you can make separate function for each type:

public void test( type1  param1) { param1.show(); }
public void test( type2  param1) { param1.show(); }
public void test(dynamic param1) { param1.show(); } // for the rest of the types

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM