如何在T1中传递函数,在T2中,在T3中,输出结果构造函数

本文关键字:输出 结果 构造函数 T3 传递函数 T1 T2 | 更新日期: 2023-09-27 18:02:38

我有一个类的构造函数,看起来像这样:

public class Class
{
 private Func<string, IThirdField, IFourthField, IResultField> resultField;
 public Class(
      IFirstField firstField,
      ISecondField secondField,
      Func<string, IThirdField, IFourthField, IResultField> resultField,
      ISomeOtherField someOtherField)
}

我试图像这样初始化这个类:

var classObject = new Class (firstField, secondField, 
Func<string, IThirdField, IFourthField, IResultField>
 resultField, someOtherField );

我得到以下错误:

  • 使用泛型'Func'需要1个类型参数

  • 无效的表达式"string".

  • "IThirdField"是一个类型,在给定的上下文中是无效的。

我做错了什么?

如何在T1中传递函数,在T2中,在T3中,输出结果构造函数

您需要传递一个响应Func签名的实例:

var obj = new Class (firstField, 
                     secondField, 
                     (stringVal, thirdFieldVal, fourthFieldVal) => default(IResultField), 
                     someOtherField);

或者如果你有一个命名函数,那么:

var obj= new Class (firstField, 
                    secondField, 
                    /*your named function*/), 
                    someOtherField);

你需要传递一个委托。有多种方法可以做到这一点,但传递匿名函数可能是最简单的:

var classObject =
    new Class(
        firstField,
        secondField, 
        (str, thrd, frth) => new ResultFieldImp()),
        someOtherField);

这里,我假设ResultFieldImp实现了IResultField。您可能需要调整此步骤来执行实际需要的操作。

您需要将其传递给Func<>

var classObject = new Class (firstField, secondField, 
(stringVal, thirdFieldVal, fourthFieldVal) => {
   // do something here
   return something;// where something is of type IResultField
},
someOtherField);

传递Func<>是一个很好的方式来定义你想要的特定输入发生什么,但不是在你给它那个方法定义的时候,如果你想用不同的实现得到不同的结果。

Linq就是一个很好的例子。你可以使用Where<T>(Func<T, bool> predicate),并给它一个定义,在Where需要使用它的时候(即在不同的迭代中),你想执行什么。因此,这使得函数执行延迟(尽管这留给您)。

在我看来,你在构造函数中传递参数给这个Func<>,并给出你想要使用这些参数执行的方法的定义。对我来说,这似乎不是最好的解决方案。

在您的示例中,最好只使用方法签名定义接口,然后定义几个实现。在我看来,你试图通过使用Func<>

来实现这一点