1

我有以下类的示例结构:

public class Base
{
}

public class Child1 : Base
{
}

public class Child2 : Base
{
}

我想做一些黑魔法:

Base @base = new Child2(); //note: there @base is declared as Base while actual type is `Child2`
var child1 = (Child1) @base;

System.InvalidCastException它按预期失败了。

然后我将隐式转换运算符添加到Child2

public class Child2 : Base
{
    public static implicit operator Child1(Child2 child2)
    {
        return new Child1();
    }
}

并且代码仍然抛出相同的异常(显式运算符也无济于事)。

您是否有任何想法如何在不使用dynamic自定义转换方法或将局部变量声明@base为的情况下解决此问题Child2

4

1 回答 1

2

您已经在 Child2 中实现了隐式转换,但实际上是在尝试从 Base 进行转换。

您应该首先将其转换为 Child2 以便隐式转换为 Child1 将适用:

var child1 = (Child1)(Child2)base;

或者

Child1 child1 = (Child2)base;

如果你不知道类型:

var child1 = base is Child1 ? (Child1)base : (Child1)(Child2)base;
var child2 = base is Child2 ? (Child2)base : (Child2)(Child1)base;

一种完全不同的方法是:

public class Base
{
    public T As<T>() where T : Base, new()
    {
        return this as T ?? new T();
    }
}

但无论如何 - 这是一个糟糕的设计,一般来说,你不应该有这样的东西。

我建议发布您的实际需求,您正在尝试做的事情,以及所有细节,并要求更好的设计/解决方案。

于 2012-05-16T11:33:58.283 回答