协变、逆变和消除多余的类型参数

发布于 2025-01-05 17:02:54 字数 990 浏览 3 评论 0原文

给定以下类层次结构:

abstract class A {  }
abstract class B {  }
abstract class C {  }
abstract class D<TA, TB, TC>
  where TA : A
  where TB : B
  where TC : C {  }

class E : A {  }
class F : B {  }
class G : C {  }
class H : D<E, F, G> {  }

我想创建一个简单的泛型方法来实例化 D 类型的对象:

void Create<TD>(string description)
  where TD : D
{
  var instance = Activator.CreateInstance<TD>();
}

但是编译器强制指定 D 的类型参数,因此我必须写以下内容:

void Create<TD, TA, TB, TC>(string description)
  where TA : A
  where TB : B
  where TC : C
  where TD : D<TA, TB, TC>
{
  var instance = Activator.CreateInstance<D>();
}

这意味着我不能写,而是

Create<H>("foo");

必须写

Create<H, E, F, G>("foo");

我的问题是:既然我指定 H 作为具体实例,为什么编译器需要附加类型方法签名上基类 D 的参数?为什么它不能简单地从 H 推断出那些?

Given the following class hierarchy:

abstract class A {  }
abstract class B {  }
abstract class C {  }
abstract class D<TA, TB, TC>
  where TA : A
  where TB : B
  where TC : C {  }

class E : A {  }
class F : B {  }
class G : C {  }
class H : D<E, F, G> {  }

I want to create a simple generic method to instantiate an object of type D:

void Create<TD>(string description)
  where TD : D
{
  var instance = Activator.CreateInstance<TD>();
}

But the compiler forces the type parameters for D to be specified, hence I have to write the following:

void Create<TD, TA, TB, TC>(string description)
  where TA : A
  where TB : B
  where TC : C
  where TD : D<TA, TB, TC>
{
  var instance = Activator.CreateInstance<D>();
}

Which means that instead of being able to write

Create<H>("foo");

I have to write

Create<H, E, F, G>("foo");

My question is: since I'm specifying H as the concrete instance, why does the compiler require the additional type parameters for the base class D on the method signature? Why can't it simply infer those from H?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

如痴如狂 2025-01-12 17:02:54

其中 TD : D 暗示 D 不是泛型,而 as where TD : D 暗示 D 是泛型。

where TD : D implies D is not generic, where as where where TD : D<TA, TB, TC> implies that D is generic.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文