1

一部のコードで「タイプ X のオブジェクトを Y にキャストできません」という例外が発生し続けます。インターフェイスとそれを実装する2つのクラスがあり、一方から他方にキャストするときにこのエラーをスローし続けます。2 つのクラスとインターフェイスは同じアセンブリの同じ名前空間にあるため、問題はありません。この混乱を解決するために分離されたコンソール アプリケーションを作成しましたが、それらを相互にキャストすることはできません。ここで基本的な .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

あなたのコードに見られる大きな間違いの 1 つは、「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

論理的な説明:

Man (クラス) には Eye (インターフェース) があり、Elephant (クラス) には Eye (インターフェース) があります。インターフェースは method() を参照してください。Man と Deer はどちらも See メソッドを持つことで Eye インターフェイスを実装しています。

、あなたがしようとしているのは、 Man オブジェクトを Elephant オブジェクトに変換することですが、これらのオブジェクトを格納するスペースにはさまざまな要件があるため、これは不可能です。

于 2012-11-05T17:15:55.410 に答える