简体   繁体   English

没有强制转换的C#隐式转换

[英]C# implicit conversion without cast

I am converting VB.net code to C# and I am facing a problem. 我正在将VB.net代码转换为C#,并且遇到了问题。 With VB.net, I have functions that use OBJECT parameters. 使用VB.net,我具有使用OBJECT参数的函数。 These parameters are usually of 2 differents types which have the same methods that I need. 这些参数通常是2种不同的类型,它们具有我需要的相同方法。 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. 使用C#,我可以执行相同的功能,但是编译器不会接受。

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. 传入的任何类型都必须实现IShowable合同,以解决该问题。

If you have Option Strict Off set using Object is the equivalent to using dynamic in C# 如果使用Object设置了Option Strict Off则等同于在C#中使用dynamic

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. 发明了dynamic来帮助编写后期绑定代码(当引入此功能时,也是VB6中提供的Job Object ),您确实应该使用带有接口的类来获取代码的强类型信息。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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