【问题标题】:Use interfaces to apply common rules to inherited interfaces使用接口将通用规则应用于继承的接口
【发布时间】:2020-05-29 03:17:20
【问题描述】:

我在不同的命名空间中有一些同名的模型,例如:

A.Request
A.Response
B.Request
B.Response

而且我有通用签名的接口:

interface IA : Common
{
  A.Response Do(A.Request);
}

interface IB : Common
{
  B.Response Do(B.Request);
}

我想创建一个所有接口都遵守的通用接口:

interface ICommon
{
  Response Do(Request);
}

但这似乎不起作用,因为它总是会尝试复制方法而不是在继承的接口上应用规则。

我尝试使用dynamicobject

interface ICommon
{
  dynamic Do(dynamic);
}

我什至尝试为模型创建一个通用接口,例如:

A.Request : IRequest
A.Response : IResponse
B.Request : IRequest
B.Response : IResponse

interface ICommon
{
  IResponse request Do(IRequest);
}

但似乎没有任何效果。

我想要的只是让这些接口具有相同的签名,实现相同的方法,但使用不同名称空间的模型,我找不到方法来做到这一点。 也许接口不打算用来对继承的接口强加通用规则,所以我想找到一种方法来做到这一点。

我想避免使用泛型,因为我已经尝试过了,但它不起作用,因为模型是密封的,你不能拥有 where IRequest: A.Requestrule。

interface ICommon
{
  Tresponse Do<TRequest,TResponse>(TRequest);
}

interface IA
{
 A.Response Do<TRequest,TResponse>(A.Request) where TRequest: A.Request, TResponse: B.Response; <- not allowed
}

【问题讨论】:

    标签: c# inheritance interface


    【解决方案1】:

    以下内容对您有用吗?

    class ARequest: IRequest {
    }
    
    class AResponse: IResponse {
    }
    
    interface IRequest {
    }
    
    interface IResponse {
    }
    
    interface ICommon<TRequest, TResponse> where TRequest: IRequest where TResponse: IResponse
    {
      TResponse Do(TRequest request);
    }
    
    interface IA: ICommon<ARequest, AResponse>
    {
       AResponse Do(ARequest r);
    }
    

    或者这个

    interface IA: ICommon<IRequest, IResponse>
    {
       AResponse Do<IRequest, IResponse>(ARequest r)
           where IRequest: ARequest 
           where IResponse: AResponse;
    }
    

    【讨论】:

    • 有前途!让我检查一下
    • 否,因为接口有多种方法。 IRequest 和 IResponse 映射到 ARequest1、ARequest2、ARequest3 等所有实现 IRequest 的类。需要在方法级别完成
    • 这个我之前已经试过了,这是不允许的,因为 ARequest 是一个密封类,编译器抱怨它不应该被密封。
    • 我尝试将 IA 和 IB 制作成实现 ICommon 的抽象类,但是它需要 IRequest 并且如果您将 A.Request 提供给抽象类,即使 A.Request 实现了 IRequest 它仍然会抱怨:(
    猜你喜欢
    • 2015-10-03
    • 1970-01-01
    • 2010-11-30
    • 1970-01-01
    • 2010-09-17
    • 2022-01-25
    • 2014-02-07
    • 1970-01-01
    相关资源
    最近更新 更多