简体   繁体   English

如何从泛型方法获得的对象中调用函数?

[英]How to call a function from an object got from generic method?

I'm relatively new to C# so please bear with me. 我是C#的新手,请耐心等待。

I don't know how to perform this operation more efficiently. 我不知道如何更有效地执行此操作。

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();

        ...
      }
  }

I would like to do something like this, or something more efficient than what I am doing now. 我想做这样的事情,或者比我现在做的更有效率的事情。 by efficient I mean that program will run faster. 高效是指程序运行速度更快。

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

Thank you for your help. 谢谢您的帮助。

You're looking for a polymorphic behavior. 您正在寻找一种多态行为。

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

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

In this case, you can define your method to constraint T to Base , and then you are allowed to use the method defined against Base but implemented by each derived class. 在这种情况下,可以定义将T约束到Base ,然后允许使用针对Base 定义但由每个派生类实现的方法。

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

You generally do not want to resort to type checking inside methods, as you seem to have already realized. 您通常不希望诉诸于方法内部的类型检查,因为您似乎已经意识到。 It's not particularly about efficiency as it is about good programming practice. 这与效率无关,因为它与良好的编程习惯有关。 Each time you add a new class, you have to come back to the method and add yet another check, which violates all kinds of solid programming practices. 每次添加新类时,都必须返回到该方法并添加另一个检查,这违反了各种可靠的编程实践。

Implement some interface for your types 为您的类型实现一些接口

public interface IMyType
{
    void DoSomething();
}

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

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

and use like 并使用像

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

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

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

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