相关疑难解决方法(0)

将List <DerivedClass>转换为List <BaseClass>

虽然我们可以从基类/接口继承,但为什么我们不能声明List<> 使用相同的类/接口?

interface A
{ }

class B : A
{ }

class C : B
{ }

class Test
{
    static void Main(string[] args)
    {
        A a = new C(); // OK
        List<A> listOfA = new List<C>(); // compiler Error
    }
}
Run Code Online (Sandbox Code Playgroud)

有办法吗?

c# collections inheritance list covariance

162
推荐指数
7
解决办法
10万
查看次数

为什么没有strings.Cast <object>将List <string>转换为List <object>?

在这个问题中有人提出,我可以将一个通用集合向上转换为一个对象集合.Cast<object>.在阅读了一下后.Cast<>,我仍然无法将它作为一个通用集合转换成另一个通用集合.以下为什么不工作?

using System.Collections.Generic;
using System.Linq;
using System;

namespace TestCast2343
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> strings = new List<string> { "one", "two", "three" };

            //gives error: cannot convert from 'System.Collections.Generic.List<string>'
            //to 'System.Collections.Generic.List<object>'
            //IEnumerable<string> items = strings.Cast<object>();

            //this works
            strings.Cast<object>();

            //but they are still strings:
            foreach (var item in strings)
            {
                System.Console.WriteLine(item.GetType().Name);
            }

            //gives error: cannot convert from 'System.Collections.Generic.List<string>'
            //to 'System.Collections.Generic.List<object>'
            ProcessCollectionDynamicallyWithReflection(strings);

            Console.ReadLine();
        }

        static void ProcessCollectionDynamicallyWithReflection(List<object> …
Run Code Online (Sandbox Code Playgroud)

c# generics

3
推荐指数
1
解决办法
921
查看次数

将具体类转换为通用基接口

这是我面临的情景:

public abstract class Record { }

public abstract class TableRecord : Record { }

public abstract class LookupTableRecord : TableRecord { }

public sealed class UserRecord : LookupTableRecord { }

public abstract class DataAccessLayer<TRecord> : IDataAccessLayer<TRecord>
    where TRecord : Record, new() { }

public abstract class TableDataAccessLayer<TTableRecord> : DataAccessLayer<TTableRecord>, ITableDataAccessLayer<TTableRecord>
    where TTableRecord : TableRecord, new() { }

public abstract class LookupTableDataAccessLayer<TLookupTableRecord> : TableDataAccessLayer<TLookupTableRecord>, ILookupTableDataAccessLayer<TLookupTableRecord>
    where TLookupTableRecord : LookupTableRecord, new() { }

public sealed class UserDataAccessLayer : LookupTableDataAccessLayer<UserRecord> { } …
Run Code Online (Sandbox Code Playgroud)

c# generics casting interface base

2
推荐指数
1
解决办法
6745
查看次数

标签 统计

c# ×3

generics ×2

base ×1

casting ×1

collections ×1

covariance ×1

inheritance ×1

interface ×1

list ×1