我在某些代码中不断获得异常“无法将类型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…
}
答案 0 :(得分: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
逻辑解释:
Man(class)有Eye(界面)和Elephant(class)有Eye(界面)。接口提供了See方法()。 Man和Deer都通过在其中使用See方法来实现Eye界面。
现在,您正在尝试将Man对象转换为Elephant对象,这是不可能的,因为存储这些对象的空间有不同的要求。