gpt4 book ai didi

C# 通用速记和向上转型

转载 作者:太空宇宙 更新时间:2023-11-03 19:52:22 24 4
gpt4 key购买 nike

我一直在研究接口(interface)和泛型。

我想要的是 Foo<T>成为 Foo<T, int> 的简写这明智吗?以下是一种公认​​的做法吗?

using System.Diagnostics;

namespace MyNamespace
{
public class Foo<T> : Foo<T, int> where T : class
{
}

public class Foo<T, U> where T : class
{
public void Bar()
{
Debug.WriteLine("this: " + GetType().Name + ", T: " + typeof(T).Name + ", U: " + typeof(U).Name);
}
}

class Program
{
static void Main(string[] args)
{
var fooT = new Foo<string>();
var fooTU = new Foo<string, int>();

fooT.Bar();
fooTU.Bar();
}
}
}

我的实际问题是...是否可以从 Foo<T, int> 向上(向下?)转换到 Foo<T>其中 T是同一类型。这么说是否有意义,或者这与协变/逆变有关(我仍然无法理解)?

对我来说,一个有点无知的人,在这个例子中Foo<string>Foo<string, int>是相同的类型,但当然是 ((Foo<string>) fooTU).Bar();不起作用!

最佳答案

What my actual question is... is it possible to up (down?) cast from a Foo<T, int> to a Foo<T> where T is the same type. Does it even make sense to say this, or is this something to do with co/contravariance (which still eludes me)?

您可以从 Foo<string, int> 转换至 Foo<string> 如果实际对象的类型是Foo<T> .它们具有相同名称的事实在这里完全无关紧要,所以让我们更改它:

class Foo<T, U> {}
class Bar<T> : Foo<T, int>

现在:

Foo<string, int> foo = new Foo<string, int>();
Bar<string> bar = (Bar<string>) foo; // Bang, throws

但是:

Foo<string, int> foo = new Bar<string>();
Bar<string> bar = (Bar<string>) foo; // This is fine

泛型在这里非常无关紧要,真的……这是正常的转换规则。

关于C# 通用速记和向上转型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37423343/

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