1

我对泛型对象有些怀疑,不知道我的想法是否可以轻松实现......

我有实现相同接口的对象,因此除了主要对象之外,方法几乎相等,如下面的代码:

public bool Func1 (Bitmap img)
{
   Obj1                 treatments    = new Obj1 ();
   List<UnmanagedImage> unmanagedList = treatments.ExtractLetters(img);

   // Check image treatments
   if (!treatments.WasSuccessful)
      return false

   return true
}

public bool Func2 (Bitmap img)
{
   Obj2                 treatments    = new Obj2 ();
   List<UnmanagedImage> unmanagedList = treatments.ExtractLetters(img);

   // Check image treatments
   if (!treatments.WasSuccessful)
      return false

   return true
}

在这种情况下,我不想复制代码。有什么简单的方法可以使这个 Obj1 和 Obj2 通用吗?因为我只能编写一个函数,然后该函数可以在对象中进行强制转换,因为其余的都是一样的。

谢谢!

4

2 回答 2

8

是的,有 - 假设所有都Treatments实现了一个ITreatments提供ExtractLetters和的通用接口WasSuccessful,你可以这样做:

interface ITreatments {
    List<UnmanagedImage> ExtractLetters(Bitmap img);
    bool WasSuccessful {get;}
}

public bool Func<T>(Bitmap img) where T : new, ITreatments
{
    T treatments    = new T();
    List<UnmanagedImage> unmanagedList = treatments.ExtractLetters(img);
    return treatments.WasSuccessful;
}

现在您可以按如下方式调用此函数:

if (Func<Obj1>(img)) {
    ...
}
if (Func<Obj2>(img)) {
    ...
}
于 2013-05-06T19:45:54.100 回答
2

仅当Obj1并且Obj2要么实现接口或继承定义ExtractLetters和的基类WasSuccessful。否则,它们是碰巧具有相同名称的不相关方法。

如果有接口或基类,您可以这样做:

public bool Func1<T>(Bitmap img) where T: ITreatments, new()
{
   T treatments = new T();
   List<UnmanagedImage> unmanagedList = treatments.ExtractLetters(img);

   // Check image treatments
   if (!treatments.WasSuccessful)
      return false

   return true
}
于 2013-05-06T19:48:47.310 回答