相关疑难解决方法(0)

通用约束,其中T:struct和T:class

我想区分以下情况:

  1. 普通值类型(例如int)
  2. 可以为null的值类型(例如int?)
  3. 引用类型(例如string) - 可选地,我不关心这是否映射到上面的(1)或(2)

我已经提出了以下代码,它适用于案例(1)和(2):

static void Foo<T>(T a) where T : struct { } // 1

static void Foo<T>(T? a) where T : struct { } // 2
Run Code Online (Sandbox Code Playgroud)

但是,如果我尝试像这样检测case(3),它就不会编译:

static void Foo<T>(T a) where T : class { } // 3
Run Code Online (Sandbox Code Playgroud)

错误消息是类型'X'已经定义了一个名为'Foo'的成员,它具有相同的参数类型.好吧,不知何故,我无法在where T : struct和之间产生影响where T : class.

如果我删除第三个函数(3),以下代码也不会编译:

int x = 1;
int? y = 2;
string z = "a";

Foo (x); // OK, …
Run Code Online (Sandbox Code Playgroud)

c# generics struct constraints class

50
推荐指数
4
解决办法
5万
查看次数

.NET 6 中的可为空性和泛型

假设我们有一些带有 2 个参数的通用方法:

private void TestConstraints<TKey>(TKey key, TKey? nullableKey)
    where TKey : notnull { }
Run Code Online (Sandbox Code Playgroud)

从 .NET6 的角度来看,这完全没问题,因为没有添加可为空的引用类型。但使用尝试失败,原因是 CS8714 类型不能用作参数:

private void TestMethod()
{
    var id = 5;
    int? nullableId = null;
    TestConstraints(id, nullableId);
}
Run Code Online (Sandbox Code Playgroud)

警告 CS8714 类型“int?” 不能用作泛型类型或方法“TestClass.TestConstraints(TKey, TKey?)”中的类型参数“TKey”。类型参数“int”的可空性?与“notnull”约束不匹配。

明确指定类型 asint没有帮助。

有人可以澄清我是否可以这样操作(将输入参数定义为TKey?),以及文档中的说明位置吗?

编译器版本:

Microsoft (R) 构建引擎版本 17.2.0+41abc5629

.net c# generics nullable-reference-types .net-6.0

10
推荐指数
1
解决办法
1126
查看次数