【问题标题】:How to declare a method in an interface with unknown count and type arguments如何在具有未知计数和类型参数的接口中声明方法
【发布时间】:2017-08-24 17:27:37
【问题描述】:

我正在尝试像这样创建 interface

public interface IProcessable<out T>
{
    T Result { get; }

    T Execute(params object[] args);
}

我想要一个返回 TExecute() 方法,并且能够接受任何类型的参数
我想这样使用它:

public class CustomProcess: IProcessable<int>
{
     public int Result { get; private set; }

     public int Execute(string customArg)
     {
         /// some codes to return int
     }
}

IProcessable&lt;int&gt; 将强制我添加一个 Execute 方法,如下所示:

public int Execute(params object[] args)
{
    var customArg= args[0] as string;
    if (customArg!= null)   //I know that this is not so necessary for `string`
    {
        return Execute(customArg);
    }

    throw new Exception();
}

我认为,我应该在CustomProcess 中同时使用这两种方法,因为object[] 的可接受范围很广。

知道我应该问:
这种接口是可以接受的还是一种反模式?
有没有更好的方法来实现我想要的-创建一个强制类具有Result 属性和Execute 方法的接口-?

【问题讨论】:

  • 一开始就为一堆都有不同签名的不同方法提供接口是没有意义的。这违背了拥有接口的全部目的。要么确保所有方法都可以使用相同的签名,要么不要使用接口,因为你什么也得不到。

标签: c# methods arguments


【解决方案1】:

正如@Servy 评论的那样,并做出正确的签名;我找到了这样的解决方案:

public interface IProcessInput
{
}

public interface IProcessable<in TInput, out TOutput> where TInput : IProcessInput
{
    TOutput Result { get; }

    TOutput Execute(TInput args);
}

public abstract class ProcessInput: IProcessInput
{
    protected ProcessInput(int count)
    {
        Count = count;
    }

    public virtual int Count { get; private set; }
}

public class WithoutProcessInput : ProcessInput
{
    public WithoutProcessInput() : base(0)
    {
    }
}

等等……

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多