简体   繁体   中英

Generic and non-generic interfaces

I come across a lot of situations where I have declared a generic interface and later I needed a non-generic version of this interface, or at least non-generic version of some of the methods or properties on that interface. I would usually declare a new non-generic interface and have it inherit the generic interface. The problem I am running into in shows in the example below:

public abstract class FormatBase { }

public interface IBook<F> where F : FormatBase
{
    F GetFormat();
}

public interface IBook
{
    object GetFormat();
}

public abstract class BookBase : IBook<FormatBase>, IBook
{
    public abstract FormatBase GetFormat();

    object IBook.GetFormat()
    {
        return GetFormat();
    }
}

Since the only way to declare the IBook (non-generic) interface is explicitly, how do you guys go about making it abstract?

Just delegate:

public abstract class BookBase : IBook<FormatBase> {
  public abstract FormatBase GetFormat();

  object IBook.GetFormat() {
    return GetFormat();
  }
}

Or, if you still want to differentiate both methods, delegate to a new method:

public abstract class BookBase : IBook<FormatBase> {
  public abstract FormatBase GetFormat();

  public abstract object IBook_GetFormat();

  object IBook.GetFormat() {
    return IBook_GetFormat();
  }
}

You also need new to dodge a "hiding inherited member" warning:

public interface IBook<F> : IBook 
where F : FormatBase {
  new F GetFormat();
}

Also, it might make more sense to let concrete classes decide on the concrete FormatBase :

public abstract class BookBase<F> : IBook<F> 
where F : FormatBase {
  public abstract F GetFormat();

  object IBook.GetFormat() {
    return GetFormat();
  }
}

Why you can't write implementation of explicit interface, instead of declaring it abstract?

public abstract class BookBase : IBook<FormatBase>, IBook
{                
    public abstract FormatBase GetFormat();

    object IBook.GetFormat()
    {
        return GetFormat();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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