Skip to main content
 首页 » 编程设计

c#之返回未知类的实例

2024年02月20日21jackei

好吧,我可能有点傻,但是否可以返回一个未知类型的值并让它获取函数?

基本上是一个看起来像...的函数

public static ?????? Test(char c) 
{ 
    if(c == char) 
        return instance of SOMECLASS 
    else 
        return instance of SOMEOTHERCLASS 
} 
 
// so i could do 
Test(new char()).SOMECLASS_METHOD(); 
Test(new int()).SOMEOTHERCLASS_METHOD(); 

谢谢

编辑:补充一下,有没有办法让它也出现在智能感知中?

请您参考如下方法:

您可以返回 dynamic(在 C# 4 或更高版本中),这样您就可以使用动态绑定(bind)。

这将允许编写任何方法,并且只有在对象上不存在该方法(或属性)时才会在运行时失败。

例如,你可以这样写:

class Foo {  
   void Bar() { Console.WriteLine("Foo.Bar"); } 
} 
 
class Bar {  
   void Baz() { Console.WriteLine("Bar.Baz"); } 
} 
 
public static dynamic Test(char c) 
{ 
   if (c == 'f') return new Foo(); 
   else return new Bar(); 
} 

有了它,你可以写:

Test('f').Bar(); 
Test('q').Baz(); 
Test('z').Bar(); // Will raise exception at runtime