相关疑难解决方法(0)

如何在C#4.0中实现通用协方差和Contra-variance?

我没有参加PDC 2008,但我听到一些消息称C#4.0被宣布支持Generic协方差和反差异.也就是说,List<string>可以分配给List<object>.怎么会这样?

在Jon Skeet的C#深度书中,解释了为什么C#泛型不支持协方差和反方差.它主要用于编写安全代码.现在,C#4.0改为支持它们.它会带来混乱吗?

有人知道有关C#4.0的细节可以给出一些解释吗?

c# covariance contravariance generic-variance c#-4.0

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

为什么我不能将List <Customer>作为参数传递给接受List <object>的方法?

以下代码给出了这个错误:

无法从'System.Collections.Generic.List'转换为'System.Collections.Generic.List'.

如何向编译器指出Customer确实从对象继承?或者它只是不与泛型集合对象继承(发送List<string>获取相同的错误).

using System.Collections.Generic;
using System.Windows;
using System.Windows.Documents;

namespace TestControl3423
{
    public partial class Window2 : Window
    {
        public Window2()
        {
            InitializeComponent();

            List<Customer> customers = Customer.GetCustomers();
            FillSmartGrid(customers);

            //List<CorporateCustomer> corporateCustomers = CorporateCustomer.GetCorporateCustomers();
            //FillSmartGrid(corporateCustomers);
        }


        public void FillSmartGrid(List<object> items)
        {
            //do reflection on items and display dynamically
        }
    }

    public class Customer
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Street { get; set; }
        public string Location { …
Run Code Online (Sandbox Code Playgroud)

c# generics

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