问题
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