1

我在某些代码中不断收到异常“无法将 X 类型的对象转换为 Y”。我有一个接口和两个实现它的类,并且在从一个转换到另一个时不断抛出此错误。这两个类和接口在同一个程序集中的同一个命名空间中,所以这不是问题。我创建了一个独立的控制台应用程序来解决这个问题,但我无法让它们相互转换。我想我在这里忘记了一些基本的.Net 规则。这段代码对你有什么影响吗?

我隔离的应用程序代码:

class Program
{
    static void Main(string[] args)
    {

        RecurringPaymentResult r = new RecurringPaymentResult();
        r.AddError("test");
        ProcessPaymentResult p = null;
        p = (ProcessPaymentResult)r; // Doesn't compile. "Cannot convert type RecurringPaymentResult to ProcessPaymentResult"
        p = (IPaymentResult)r; // Doesn't compile. "Cannot convert type RecurringPaymentResult to ProcessPaymentResult. An explicit conversion exists (are you missing a cast?)"
        p = (ProcessPaymentResult)((IPaymentResult)r); // Compiles but throws: "Unable to cast object of type RecurringPaymentResult to ProcessPaymentResult" during runtime
    }
}

我的核心代码:

public interface IPaymentResult
{
    IList<string> Errors { get; set; }
    bool Success { get; }
    void AddError(string error);
}

public partial class RecurringPaymentResult : IPaymentResult
{
    public IList<string> Errors { get; set; }

    public RecurringPaymentResult() 
    {
        this.Errors = new List<string>();
    }

    public bool Success
    {
        get { return (this.Errors.Count == 0); }
    }

    public void AddError(string error) 
    {
        this.Errors.Add(error);
    }
}


public partial class ProcessPaymentResult : IPaymentResult
{
    private PaymentStatus _newPaymentStatus = PaymentStatus.Pending;
    public IList<string> Errors { get; set; }

    public ProcessPaymentResult() 
    {
        this.Errors = new List<string>();
    }

    public bool Success
    {
        get { return (this.Errors.Count == 0); }
    }

    public void AddError(string error)
    {
        this.Errors.Add(error);
    }

    // More properties and methods here…

}
4

1 回答 1

0

我在您的代码中看到的一个主要错误是说“ p = ”。

您已经决定了p的类型,并且您在这种类型中分配了各种其他变量,这是错误的。

以下是所有可能的转换:

RecurringPaymentResult r = new RecurringPaymentResult();
r.AddError("test");
ProcessPaymentResult p = null;

var r1 = (IPaymentResult)r;  //type of r1 becomes IPaymentResult
var r2 = (IPaymentResult)p;  //type of r2 becomes IPaymentResult
var r3 = (RecurringPaymentResult)r1; //type of r3 becomes RecurringPaymentResult 
var r4 =  (ProcessPaymentResult)r2; //type of r4 becomes ProcessPaymentResult

逻辑解释:

人(类)有眼睛(接口),大象(类)有眼睛(接口)。接口提供 See method()。Man 和 Deer 都通过在其中包含 See 方法来实现 Eye 接口。

现在,您正在尝试将 Man 对象转换为 Elephant 对象,这是不可能的,因为存储这些对象的空间有不同的要求。

于 2012-11-05T17:15:55.410 回答