如何从泛型方法获得的对象调用函数
本文关键字:对象 调用 函数 泛型方法 | 更新日期: 2023-09-27 18:10:47
我对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();
}
}
谢谢你的帮助。
您正在寻找多态行为。
abstract class Base // could also simply be interface, such as ICanDoSomething
{
public abstract void DoSomething();
}
class MyClass1 : Base
{
public override void DoSomething() { /* implement */ }
}
在这种情况下,您可以定义您的方法来约束T
到Base
,然后您可以使用针对Base
定义的方法,但由每个派生类实现。public static void Foo<T>(LinkedList<T> list) where T : Base // or T : ICanDoSomething
{
foreach (T item in list)
{
item.DoSomething();
}
}
您通常不希望在方法中使用类型检查,正如您似乎已经意识到的那样。它不是特别关于效率,而是关于良好的编程实践。每次添加新类时,都必须回到方法并添加另一个检查,这违反了各种坚实的编程实践。
为你的类型实现一些接口
public interface IMyType
{
void DoSomething();
}
public class MyType1 : IMyType
{
public void DoSomething() { }
}
public class MyType2 : IMyType
{
public void DoSomething() { }
}
和使用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();
}
}