gpt4 book ai didi

c# - Func<> 的 List<>,具有通用返回类型的编译错误,但为什么呢?

转载 作者:可可西里 更新时间:2023-11-01 03:06:53 25 4
gpt4 key购买 nike

这个问题有点长,所以请耐心等待。

我需要在一组字符串和每个字符串对应的通用方法调用之间创建一个映射。但是,我遇到了一个编译问题,下面进行了解释。

在我的场景中,我使用的是 Dictionary<> ,但问题同样存在于 List<> .为简单起见,我使用 List<>在下面的示例中。

考虑这三个类:

public abstract class MyBase { /* body omitted */  }
public class MyDerived1 : MyBase { /* body omitted */ }
public class MyDerived2 : MyBase { /* body omitted */ }

还有一些其他类中的方法:

public class Test
{
public T GetT<T>() where T : MyBase { /* body omitted */ }
}

在另一个类中,我可以声明一个 List<Func<MyBase>>像这样:

public class SomeClass
{
public void SomeFunc()
{
var test = new Test();

var list1 = new List<Func<MyBase>>
{
test.GetT<MyDerived1>,
test.GetT<MyDerived2>
};
}
}

这一切都很好。

但是,如果我想要一个像这样返回泛型类的函数怎么办:

public class RetVal<T> where T : MyBase { /* body omitted */ }

public class Test
{
public RetVal<T> GetRetValT<T>() where T : MyBase
{
return null;
}
}

我想创建一个等效的 List<>使用此功能。即列表>>?

public class Class1
{
public void SomeFunc()
{
var test = new Test();

var list2 = new List<Func<RetVal<MyBase>>>
{
test.GetRetValT<MyDerived1>, // compile error
test.GetRetValT<MyDerived2> // compile error
};
}
}

我得到 Expected a method with 'RetVal<MyBase> GetRetValT()' signature 的编译错误.

那么,有没有办法解决这个问题,或者是否有其他方法可以用来创建我的字符串...通用方法调用映射?

最佳答案

C# 只允许接口(interface)上的协变。这意味着你不能转换 RetVal<MyDerived1>RetVal<MyBase>自动地。如果RetVal应该是协变的,为它创建一个接口(interface),如下所示:

public interface IRetVal<out T>
{

}
public class RetVal<T> : IRetVal<T> where T : MyBase { /* body omitted */ }

public class Test
{
public IRetVal<T> GetRetValT<T>() where T : MyBase
{
return null;
}
}

然后这段代码就可以工作了:

    var list2 = new List<Func<IRetVal<MyBase>>>
{
test.GetRetValT<MyDerived1>,
test.GetRetValT<MyDerived2>
};

关于c# - Func<> 的 List<>,具有通用返回类型的编译错误,但为什么呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10554435/

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