相关疑难解决方法(0)

C#中的继承和容器

我在这里工作,让我说我有:

class A
{}

class B : A
{}

List<B> myList;
Run Code Online (Sandbox Code Playgroud)

我想,在代码的一部分中投射此myList,List< A>,但是当我尝试时,我收到一个错误:

List<A> myUpcastedList = (List<A>)myList; //not working
Run Code Online (Sandbox Code Playgroud)

有可能做到吗?如果是的话,语法是什么?

c# inheritance containers upcasting

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

什么时候应该或不应该使用泛型类型约束?

我有一个基类:

public abstract class StuffBase
{
    public abstract void DoSomething();
}
Run Code Online (Sandbox Code Playgroud)

还有两个派生类

public class Stuff1 : StuffBase
{
    public void DoSomething()
    {
        Console.WriteLine("Stuff 1 did something cool!");
    }
    public Stuff1()
    {
        Console.WriteLine("New stuff 1 reporting for duty!");
    }
}

public class Stuff2 : StuffBase
{
    public void DoSomething()
    {
        Console.WriteLine("Stuff 2 did something cool!");
    }
    public Stuff1()
    {
        Console.WriteLine("New stuff 2 reporting for duty!");
    }
}
Run Code Online (Sandbox Code Playgroud)

好的,现在说我有一个项目列表:

var items = new List<StuffBase>();
items.Add(new Stuff1());
items.Add(new Stuff2());
Run Code Online (Sandbox Code Playgroud)

我希望他们都能调用他们的DoSomething()方法.我可以期望只是迭代列表并调用他们的DoSomething()方法,所以让我们说我有一个方法来做这个叫做AllDoSomething()的方法只是遍历列表并完成工作:

public static void …
Run Code Online (Sandbox Code Playgroud)

c# generics type-constraints c#-2.0

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

如何创建具有继承的泛型类?

如何使以下代码有效?我不认为我完全理解C#泛型.也许,有人可以指出我正确的方向.

    public abstract class A
    {
    }

    public class B : A
    {
    }

    public class C : A
    {
    }

    public static List<C> GetCList()
    {
        return new List<C>();
    }

    static void Main(string[] args)
    {
        List<A> listA = new List<A>();

        listA.Add(new B());
        listA.Add(new C());

        // Compiler cannot implicitly convert
        List<A> listB = new List<B>();

        // Compiler cannot implicitly convert
        List<A> listC = GetCList();

        // However, copying each element is fine
        // It has something to do with generics (I think) …
Run Code Online (Sandbox Code Playgroud)

c# inheritance covariance contravariance

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