removing redundant type in Interface

拈花ヽ惹草 提交于 2020-01-15 08:15:12

问题


I have following interfaces

public interface IRevision<TRevisionType>
{ ... }

public interface IRevisionLog
{ ... }

public interface IRevisionControl<in TRevision, TLogType,T>
  where TRevision : IRevision<T> 
  where TLogType : IRevisionLog
{ ... }

This code compiles fine, but I am wondering, is this last one T really needed? When i implement IRevision I will be passing type T, so there is really no need to duplicate type.

My demo implementation would be:

public class HgRevision : IRevision<string>
{ ...}

public class HgLog : IRevisionLog
{ ... }

public class Hg : IRevisionControl<HgRevision, HgLog, string>

I'm passing string twice. I'm wondering if i could do anything like this:

public interface IRevisionControl<in TRevision, TLogType>
  where TRevision : IRevision
  where TLogType : IRevisionLog
{ ... }

So my Hg would be:

public class Hg : IRevisionControl<HgRevision, HgLog>

Of course, this last snippet does not compile.


回答1:


This code compiles fine, but I am wondering, is this last one T really needed?

Yes, assuming you actually need the constraint on TRevision. If you don't, that's fine... but if you do, you need to be able to specify which IRevision<T> there has to be a conversion to.

One option would be to create a base interface for IRevision<>:

public interface IRevision
{
    // Include any members which don't depend on TRevisionType
}

public interface IRevision<TRevisionType> : IRevision
{
    // The rest
}

Then you can just use:

public interface IRevisionControl<in TRevision, TLogType>
  where TRevision : IRevision 
  where TLogType : IRevisionLog

... but of course you then won't be able to use any of the members declared in IRevision<> - only the ones in the non-generic base interface.




回答2:


Are you sure, that you need TRevision in declaration of IRevisionControl? I mean, it would make sense in class declaration, because some code in the class methods can work only with specific TRevision, but in interface, maybe, this will be enough:

public interface IRevisionControl<TRevisionType, TLogType>
  where TLogType : IRevisionLog
{
     void Foo(IRevision<TRevisionType> revision);
}

?



来源:https://stackoverflow.com/questions/17912445/removing-redundant-type-in-interface

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!