相关疑难解决方法(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万
查看次数

标签 统计

c# ×1

class ×1

constraints ×1

generics ×1

struct ×1