1

我怎样才能做类似以下的事情?
我的A对象在调用后为空,GetB即使A继承自B.

class Program
{
    public class A : B
    {
    }

    public class B
    {
    }

    static void Main(string[] args)
    {
        A a = GetB() as A;
        Console.WriteLine(a == null); // it is null!

        Console.WriteLine("Console.ReadKey();");
        Console.ReadKey();
    }
    public static B GetB()
    {
        return new B();
    }
}
4

4 回答 4

4

You probably meant return new A(); in the function. At the moment, you're trying to down-cast your B to an A, which won't work.

于 2012-05-09T23:50:34.147 回答
1

You got it reversed:

class Program
{
    public class A : B  // should be: public class A
    {
    }

    public class B // should be: public class B : A
    {
    }

    static void Main(string[] args)
    {
        // If you reverse the inheritance on code above
        // As Ben Voigt noticed, *as A* is redundant. should be removed
        // A a = GetB() as A; 

        // should be this. B is wider than A, so A can accept B, no need to cast
        A a = GetB(); 
        Console.WriteLine(a == null); // it is null!

        Console.WriteLine("Console.ReadKey();");
        Console.ReadKey();
    }
    public static B GetB()
    {
        return new B();
    }
}
于 2012-05-09T23:52:33.663 回答
1

你正试图将你的 B 降级为 A。你不能这样做,也没有意义,因为我们不知道 B 是否会成为 A。最好在你的A类中构建一个构造函数以 aB作为参数。

public class A : B
{
    public A(B b)
    {
        //perform your conversion of a B into an A
    }
}

public class B
{
    public B(){}
}

static void Main(string[] args)
{
    B b = new B();
    A a = new A(b);
    Console.WriteLine(a == null); // it is null!

    Console.WriteLine("Console.ReadKey();");
    Console.ReadKey();
}
于 2012-05-10T00:01:58.720 回答
1

您将无法执行这种类型的铸造,因为B很可能不是A!当然,A是 的子类B,因此您始终可以执行GetA() as B;. 但是走另一条路是没有意义的。最有可能的一个实例AB.

考虑添加第三类,C : B. 如果您的函数GetB()实际上返回了 anew C()怎么办?这很好,因为CB. 但是您当然不希望能够将其转换为A? A并且C几乎可以肯定几乎没有共同点。

于 2012-05-09T23:54:12.680 回答