2014-06-23 46 views
0

如果我有做一些操作(即工作分为以下两种类型之一),并且需要两个不同类型的工作参数的函数,是有一些不错的方法,使像public void foo(typeX x || typeY x)一个方法,不同的参数

例子:

void main(bool b) 
{ 
    if(b) 
    { 
     List<int> x = new List<int>(); 
     x.Add(5); 
    } 
    else 
    { 
     Collection<int> x = new Collection<int>(); 
     x.Add(5); 
    } 
    foo(x); 
} 

我看到它的方式,这留下了两个选项。

选项1:

void foo(List<int> x) 
{ 
    Console.WriteLine(x.ToString()); 
} 

void foo(Collection<int> x) 
{ 
    Console.WriteLine(x.ToString()); 
} 

为什么不呢?因为如果void foo()比仅仅几行更长,看起来很丑陋,没有必要。

选项2:

void foo(Object x) 
{ 
    Console.WriteLine(x.ToString()); 
} 

为什么不呢?对于这个简单的例子来说很好,但是如果foo应该做一些不是每个对象都有的东西,比如x.Add(1);,那么我们会得到一个错误,说Object没有这个方法。

有没有人知道一些天才的华丽sollution这个?或者我坚持选择1?

+0

如果你的类型不是东西,如原语或集合,你为什么不只是创建一个接口,让想类型为富处理? –

回答

2

在这种情况下,List<int>Collection<int>都实现IList<int>接口(等等)。因此,假设代码不是特定于一个或另一个这些类型的,你应该能够使用该接口:

void foo(IList<int> x) 
{ 
    Console.WriteLine(x.ToString()); 
} 

这个答案的通用版本 - 这适用于你写的类 - 你应该为有问题的类型创建一个接口。假设你有一个TypeXTypeY如您在问题之初声明:

interface ICanFoo 
{ 
    string Foo(); 
} 

class TypeX : ICanFoo 
{ 
    public string Foo() 
    { 
     return "I'm a TypeX!"; 
    } 
} 

class TypeY : ICanFoo 
{ 
    public string Foo() 
    { 
     return "I'm a TypeY!"; 
    } 
} 

void foo(ICanFoo x) 
{ 
    Console.WriteLine(x.Foo()); 
} 
+0

谢谢。我正在寻找更一般的方式:)界面看起来不错 –

相关问题