这些通用参数约束是什么意思?

What does these generic parameter constraints mean?

我正在使用一个将此作为第一个参数的方法:

Action<IFieldsetter<Contact>>

我该如何阅读?这是否意味着这必须是一个 Action 对象,其中 Action 构造函数被限制为只接受实现 IFieldsetter 的东西?而且貌似IFieldsetter本身是被约束了,但是这部分我完全看不懂

这不是实际的约束,而只是它需要的类型。因此,该方法的第一个参数是一个 Action(即 delegate),它只有一个参数,而那个参数是一个 IFieldsetter<Contact>,不管它是什么意思。我的猜测是 IFieldsetter 公开了一个 setter 并且在这种情况下它必须处理类型 Contact,但是您应该是真正知道它们是什么和做什么的人! Post 这个接口的代码和这个 class 如果你需要进一步的帮助。

例如,如果它是 Action<IEnumerable<String>>,则表示委托接收一个字符串列表作为参数。这是一些代码:

// Your method with the *special* parameter.
private void ChrisMethod(Action<IEnumerable<String>> method)
{
    string[] exampleList = { "First", "Second", "Third" };
    method(exampleList);
}

// The method that can be used as parameter.    
private void ParameterMethod(IEnumerable<String> list)
{
    foreach(string str in list)
        Console.WriteLine(str);
}

public void Main()
{
    ChrisMethod(ParameterMethod);
}

类型参数的约束是另一回事。您可以了解更多相关信息 here

C# System.Action (MSDN) 是一个委托对象,其中 Action<T> 等效于匹配 void FunctionName(T) 的委托函数。所以你可以将它设置为一个函数,然后调用该函数。

泛型块 <Contact> 适用于 IFieldsetter,因此您有一个接受参数 IFieldsetter<Contact> 的操作。在对 IFieldsetter 一无所知的情况下,我无法告诉您它与那里的 Contact 泛型参数有什么关系。

为了使用它,您将拥有类似于以下内容的内容:

void Main()
{
    FunctionThatDoesStuff(SetField);
}
void FunctionThatDoesStuff(Action<IFieldsetter<Contact>> action)
{
    var setter = new IFieldsetter<Contact>();
    action(setter);
}
void SetField(IFieldsetter<Contact> setter)
{
}

这是嵌套泛型类型参数。从最外层可以看出这是一个Action<T>委托。委托需要一个类型为 T 的参数。在这种情况下,T 被替换为 IFieldsetter<Contact>。即 Action<IFieldSetter<Contact>> 需要一个类型为 IFieldSetter<Contact> 的参数。现在 IFieldSetter<T> 接口设置了一个类型为 T 的字段。在这种情况下,T 被替换为 Contact 所以 IFieldSetter<Contact> 设置了一个类型为 Contact.[=22= 的字段]

总结一下:Action<IFieldsetter<Contact>> 表示一个 Action 委托,它需要一个 IFieldSetter 类型的参数,它可以设置一个 Contact 类型的字段.现在你明白了吗?

Action<IFieldsetter<Contact>> 表示 Action 委托接受一个实现通用接口 IFieldsetter 的类型的参数。假设 class 是通过 IFieldsetter intercae 实现的,其中 Contact 作为通用参数,如下所示。

public class Test: IFieldsetter<Conatct>
{

}

现在可以将此测试的实例 class 作为参数传递给 Action deletegate。