Type parameter 'T' has the same name as the type parameter from outer type '…'

前端 未结 3 1213
执念已碎
执念已碎 2021-01-07 19:06
public abstract class EntityBase { ... }

public interface IFoobar
{
    void Foo(int x)
        where T : EntityBase, new();
}

public interface IFoobar<         


        
3条回答
  •  余生分开走
    2021-01-07 19:27

    The biggest problem is that your interfaces are not well defined, and do not match the intent of your code.

    If your T is not publicly visible on the interface, then external code doesn't even have to know there is a T. You need to either make methods that receive or return T, or have some property of type T, or you should simply get rid of T entirely, and make your interfaces non-generic.

    Once you shore this up, it should become more obvious why you don't need two different interfaces here, and you should no longer have to reconcile them.

    If it turns out that you do need a version that takes T, and a non-T version, then the more idiomatic way to do this is pass around object instead of T:

    public interface IFoo
    {
        void DoSomething(object o);
        object DoSomethingElse();
    }
    
    public interface IFoo
    {
        void DoSomething(T item);
        T DoSomethingElse();
    }
    

    See interfaces like IEnumerable, ICollection, IList, etc for examples of this.

    But consider carefully. This last design compromise (having both a generic and object version) always leaves something to be desired.

    You'll sacrifice one of these:

    • Good interface design that directly communicates a design contract (If you throw exceptions or do a no-op when the wrong type is passed in)
    • Type safety, and the reduction in bugs that goes with it (if you correctly operate on any-old-object)

提交回复
热议问题