2011-10-07 66 views
0

我对C#比较陌生,所以请耐心等待。如何从通用方法获得的对象调用函数?

我不知道如何更有效地执行此操作。

public static void Foo<T>(LinkedList<T> list) 
{ 
    foreach (Object o in list) 
    { 
     if (typeof(o) == typeof(MyClass1)) 
      (MyClass1)o.DoSomething(); 
     else if (typeof(o) == typeof(MyClass2)) 
      (MyClass2)o.DoSomething(); 

     ... 
     } 
    } 

我想做类似这样的事情,或者比我现在做的更有效的事情。通过高效率,我的意思是这个程序运行得更快

public static void Foo<T>(LinkedList<T> list) 
{ 
    foreach (Object o in list) 
    { 
     o.DoSomething(); 
     } 
    } 

谢谢你的帮忙。

+0

做的项目需要以相同的顺序被称为?你见过'OfType'吗? –

+1

你可以使用接口吗? –

+0

btw'typeof'是编译时的东西。你需要检查'null',然后使用'o.GetType()' –

回答

2

您正在寻找多态行为。

abstract class Base // could also simply be interface, such as ICanDoSomething 
{ 
    public abstract void DoSomething(); 
} 

class MyClass1 : Base 
{ 
    public override void DoSomething() { /* implement */ } 
} 

在这种情况下,你可以定义你的方法来约束TBase,然后你被允许使用定义Base每个派生类中实现的方法。

public static void Foo<T>(LinkedList<T> list) where T : Base // or T : ICanDoSomething 
{  
    foreach (T item in list) 
    { 
     item.DoSomething(); 
    } 
} 

您通常不希望诉诸类型检查内部方法,因为您似乎已经实现了。这不是特别关于效率,因为它是关于良好的编程习惯。每次添加新课程时,都必须回到方法并添加另一个校验,这违反了所有种类的实体编程实践。

2

实现一些接口,为您的类型

public interface IMyType 
{ 
    void DoSomething(); 
} 

public class MyType1 : IMyType 
{ 
    public void DoSomething() { } 
} 

public class MyType2 : IMyType 
{ 
    public void DoSomething() { } 
} 

,并使用像

public static void Foo<T>(LinkedList<T> list) where T: IMyType 
{ 
    foreach (T o in list) 
    { 
     o.DoSomething(); 
     } 
    } 
1
public interface IDoSomething 
{ 
    void DoSomething(); 
} 

public static void Foo<T>(LinkedList<T> list) where T : IDoSomething 
{ 
    foreach (T o in list) 
    { 
     o.DoSomething(); 
    } 
} 
相关问题