如何创建泛型方法

时间:2010-10-13 22:35:47

标签: c# .net generics polymorphism casting

我想创建一个方法,它将一些基类型作为参数,并比较并检查它是否是派生类型,并根据它返回派生类型。 例如:

Class A : IBase
Class B : IBase

我的方法:

Public IBase GetData(IBase type)
{
 If type is A then 
  {
   //do smthing
   return A
  }
 If type is B
  {
   //do smthing
   return B
  }
} 

请帮助.....

4 个答案:

答案 0 :(得分:4)

您应该在代码标记为//do something的位置执行您要执行的步骤,并将其封装到类的方法中,我们称之为DoSomething()。您将要向IBase接口添加一个名为DoSomething()的公共方法。然后,类型A和类型B都将实现此接口,并为此“Do Something”方法提供不同的实现。

然后,你的方法就是:

public IBase GetData(IBase type)
{
    type.DoSomething();
    return type; //not sure what this is for, maybe you're actually wanting to return type.GetType() ??
} 

有关如何使用多态来消除对这些类型的if语句的需求的更多详细信息,请参阅文章Replace Conditional with Polymorphism

答案 1 :(得分:3)

我从技术上讲,正确使用多态性应该完全不需要进行类型检查。

但是,声明类型参数必须实现接口的泛型函数是这样的:

public TBase GetData<TBase>(TBase type) where TBase : IBase

如果您确实想继续进行特定的类型检查,那么可以使用Type.IsAssignableFrom功能。

public TBase GetData<TBase>(TBase type) where TBase : IBase
{
    if (typeof(A).IsAssignable(typeof(TBase)))
    {
        // Do the special case stuff
    }
    ...
}

但是当我开始提及时,或许将特殊情况的东西移到IBase界面本身更合适。

答案 2 :(得分:2)

此:

public T GetData<T>(T type) where T : IBase
{
   ....
}

答案 3 :(得分:0)

泛型在这里有点矫枉过正。让我们试试反思:

IBase type = GetSomeObjectOfDescendantType();
IBase newType = (IBase)Activator.CreateInstance(type.GetType());

您可以将其包装在方法

public class MyDuplicator
{
    public static object GetNotClone(object X)
    {
        return Activator.CreateInstance(X.GetType());
    }
}

有关CreateInstance here的更多信息。

当然,只有当你的问题是关于返回类型A的对象时才适用,如果要放入类型A的对象。作为.Clone()的东西,但是新构造的东西。

相关问题