gpt4 book ai didi

c# - 为什么开放泛型的基类型不开放?

转载 作者:可可西里 更新时间:2023-11-01 03:00:56 24 4
gpt4 key购买 nike

考虑下面的一段代码:

public class A<T> { }

public class B<T> : A<T> { }

在这种情况下:

var a = typeof(A<>).GenericTypeArguments.Length;

a 的值为 0,这并不奇怪。然而,这对我来说有点出乎意料:

var b = typeof(B<>).BaseType.GenericTypeArguments.Length;

其中 b 的值为 1。因此它使用不存在的类型名称“T”关闭,并且仅对其执行 GetGenericTypeDefinition 使其再次打开。这是为什么?

最佳答案

So it is closed using a non-existing type of name "T" and only doing GetGenericTypeArgument on it makes it open again. Why is that?

因为 提供了一个类型参数 - B 的类型参数.

看看你是如何指定基类的:

public class B<T> : A<T>

什么是 TA<T>如果它不是类型参数?仅仅因为类型参数本身是类型参数并不意味着它没有被指定为类型参数。

考虑一下:

public class A<T1, T2> { }

public class B<T> : A<T, int> { }

在这里,B<T> 的基类是A<T, int> - 你可以确定 int已通过询问类型参数指定。您还可以显示 T 在哪里来自:

using System;
using System.Reflection;
using System.Collections.Generic;

public class A<T1, T2> { }

public class B<T> : A<T, int> { }

class Program
{
static void Main()
{
var bT = typeof(B<>).GetTypeInfo().GenericTypeParameters[0];
var listT = typeof(List<>).GetTypeInfo().GenericTypeParameters[0];
var bBaseArguments = typeof(B<>).BaseType.GenericTypeArguments;
Console.WriteLine(bBaseArguments[0] == bT); // True
// Shows that the T from B<T> isn't the same as the T from List<T>
Console.WriteLine(bBaseArguments[0] == listT); // False
Console.WriteLine(bBaseArguments[1] == typeof(int)); // True
}
}

关于c# - 为什么开放泛型的基类型不开放?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32091197/

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