方法内部的通用对象

bre*_*iba 1 c# c#-4.0

我对通用对象有一些疑问,我不知道我的想法是否可以轻松实现......

我有对象实现相同的接口,所以方法几乎等于主要对象,如下面的代码:

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
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我不想复制代码.有没有简单的方法使这个Obj1和Obj2通用?因为我只能编写一个函数,然后函数可以在对象中执行转换,因为其余的是相同的.

谢谢!

das*_*ght 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;
}
Run Code Online (Sandbox Code Playgroud)

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

if (Func<Obj1>(img)) {
    ...
}
if (Func<Obj2>(img)) {
    ...
}
Run Code Online (Sandbox Code Playgroud)