方法接受接口(interface)-6ren"> 方法接受接口(interface)-我有这个interface : public interface ITestInterface { int TestInt { get; set; } } 和这个通用方法(带有 T : cla-6ren">
gpt4 book ai didi

c# - 为什么具有 "where T : class"约束的 Generic 方法接受接口(interface)

转载 作者:可可西里 更新时间:2023-11-01 08:25:49 25 4
gpt4 key购买 nike

我有这个interface :

public interface ITestInterface
{
int TestInt { get; set; }
}

和这个通用方法(带有 T : class 约束):

public void Test<T>() where T : class
{
// DoSomething
}

这个电话:

Test<ITestInterface>();

一切都编译并运行,同时 interface 不是 class (或者是吗?)。

为什么会这样?

我第一次看到这个是在我的 WCF 代理类上:

public partial class TestServiceClient:
System.ServiceModel.ClientBase<TestNamespace.ITestService>, TestNamespace.ITestService

哪里ClientBase<T>有这个定义:

public abstract class ClientBase<TChannel> : 
ICommunicationObject, IDisposable where TChannel : class

最佳答案

class 约束意味着类型必须是引用类型,不一定是类。

来自 C# 语言规范:

The reference type constraint specifies that a type argument used for the type parameter must be a reference type. All class types, interface types, delegate types, array types, and type parameters known to be a reference type (as defined below) satisfy this constraint.

基本上,这意味着该类型不能是值类型。

值类型也可以实现接口(interface),但是将值类型转换为接口(interface)会导致值被装箱

IComparable i = 0;

现在 i 存储对装箱的 0 的引用。

关于c# - 为什么具有 "where T : class"约束的 Generic<T> 方法接受接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33720381/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com