相关疑难解决方法(0)

为什么协方差和逆变不支持值类型

IEnumerable<T>共变体,但它不支持值类型,仅支持引用类型.以下简单代码编译成功:

IEnumerable<string> strList = new List<string>();
IEnumerable<object> objList = strList;
Run Code Online (Sandbox Code Playgroud)

但是从更改stringint将得到编译错误:

IEnumerable<int> intList = new List<int>();
IEnumerable<object> objList = intList;
Run Code Online (Sandbox Code Playgroud)

原因在MSDN中解释:

差异仅适用于参考类型; 如果为变量类型参数指定值类型,则该类型参数对于生成的构造类型是不变的.

我搜索过并发现有些问题提到的原因是值类型和引用类型之间的装箱.但它仍然不清楚我的想法为什么拳击是什么原因?

有人可以给出一个简单而详细的解释为什么协方差和逆变不支持值类型以及拳击如何影响这个?

.net c# covariance contravariance c#-4.0

144
推荐指数
3
解决办法
8497
查看次数

理解C#中的Covariant和Contravariant接口

我在C#上阅读的教科书中遇到过这些,但我很难理解它们,可能是由于缺乏背景.

是否有一个很简洁的解释,说明它们是什么以及它们对那里有用的东西?

编辑以澄清:

协变界面:

interface IBibble<out T>
.
.
Run Code Online (Sandbox Code Playgroud)

逆变接口:

interface IBibble<in T>
.
.
Run Code Online (Sandbox Code Playgroud)

.net c# interface covariance contravariance

82
推荐指数
2
解决办法
2万
查看次数

How to make a method generic when "type 'T' must be a reference type"?

Possible Duplicate:
Why do I get “error: … must be a reference type” in my C# generic method?

I have 2 Repository methods that are almost identical:

public IList<Fund> GetFundsByName(int pageSize, string searchExpression)
{
    return _session.CreateCriteria<Fund>()
        .AddNameSearchCriteria<Fund>(searchExpression)
        .AddOrder<Fund>(f => f.Name, Order.Asc)
        .SetMaxResults(pageSize).List<Fund>();
}

public IList<Company> GetCompaniesByName(int pageSize, string searchExpression)
{
    return _session.CreateCriteria<Company>()
        .AddNameSearchCriteria<Company>(searchExpression)
        .AddOrder<Company>(f => f.Name, Order.Asc)
        .SetMaxResults(pageSize).List<Company>();
}
Run Code Online (Sandbox Code Playgroud)

The only difference is that the first one's _session.CreateCriteria is of type Fund and the second one is company

I was …

c# generics nhibernate

78
推荐指数
2
解决办法
5万
查看次数

为什么协方差不适用于泛型方法

假设我有接口和类:

public interface ITree {}
public class Tree : ITree {}
Run Code Online (Sandbox Code Playgroud)

由于IEnumerable<T>协变,下面的代码行成功编译:

IEnumerable<ITree> trees = new List<Tree>();
Run Code Online (Sandbox Code Playgroud)

但是当我把它放入通用方法时:

public void Do<T>() where T : ITree
{
     IEnumerable<ITree> trees = new List<T>();
}
Run Code Online (Sandbox Code Playgroud)

我从编译器得到编译错误:

错误1无法将类型'System.Collections.Generic.List'隐式转换为'System.Collections.Generic.IEnumerable'.存在显式转换(您是否缺少演员?)D:\ lab\Lab.General\Lab.General\Program.cs 83 40 Lab.General

为什么协方差在这种情况下不起作用?

c# covariance contravariance c#-4.0

23
推荐指数
1
解决办法
1987
查看次数

什么时候在C#中有用的值类型/引用类型约束?

我正在寻找简单的示例来演示值类型/引用类型约束何时有用.

... where T : struct  // when is this useful?
... where T : class   // and what about this?
Run Code Online (Sandbox Code Playgroud)

我记得过去看过一些非常好的例子,但我找不到它们.

c# generics constraints

6
推荐指数
1
解决办法
2433
查看次数