gpt4 book ai didi

c# - 转换为泛型方法不支持的基类型

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

我有一个接口(interface) IGenericOrder如下:

using System;
using System.Linq.Expressions;

namespace MyNamespace
{
interface IGenericOrder<T> where T : new()
{
Func<T, int> GetStatement(string name);
}


public class GenericOrder<T> : IGenericOrder<T> where T : new()
{
public Func<T, int> GetStatement(string name)
{
return (T) => 4;
}
}
}

现在,当我创建该类的实例并将其转换回 IGenericOrder<object>

var sorter = (IGenericOrder<object>) new GenericOrder<Foo>();

我得到异常:

InvalidCastException: The instance of type GenericOrder<Foo> cannot be cast to IGenericOrder<object>

界面看起来很清楚IGenericOrder不是协变的。但是,如果我使接口(interface)协变(interface IGenericOrder<out T>),我会得到一个编译器错误:

Invalid variance: The type parameter 'T' must be contravariantly valid on IGenericOrder<T>.GetStatement(string). 'T' is covariant.

正如我从 here 中读到的那样协方差只能在以下情况下使用

[the generic type parameter] is used only as a method return type and is not used as a type of formal method parameters.

这是否意味着我不能对自身返回通用实例的方法使用协变/逆变?

我正在使用 .Net 4.5

最佳答案

要了解发生了什么,请查看 Func<T,TResult> 的定义代表:

public delegate TResult Func<in T, out TResult>(
T arg
)

如你所见,它的第一个类型参数T是一个 in范围。因此,您不能使用 out参数为 Func的第一个类型参数。第二类参数TResultout , 所以使用 T作为TResult会工作:

interface IGenericOrder<out T> where T : new() {
Func<int,T> GetStatement(string name);
}

public class GenericOrder<T> : IGenericOrder<T> where T : new() {
public Func<int,T> GetStatement(string name) {
return (x) => default(T);
}
}

Demo.

关于c# - 转换为泛型方法不支持的基类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34337616/

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