2

What I'm basically trying to do is Convert Objects I get from a web Service to objects that are compatible with my Entity Framework object. I though of doing this by creating an Interface that both is applied to the web service objects & the EF objects. That way I can easily cast from one type to the other. At this point I have the following object: A, A1, B and interface IAB.

The problem I'm no facing is when I do an upcast from object A to A1 I get a Run-time error but no compile errors. I would like to know why my upcast isn't accepted?

public class A
{
  //Has variables & Properties
}

public class A1 : A, IAB
{
  //Has some properties
}

Note: I needed to create A1 as extending the partial class A created Serialization problems for the web service. So this seemed to be the best solution.

When contacting the service I ask for a list of A objects and then want to upcast them to A1. Later I will cast them into B.

I try to cast the objects like this:

 List<A1> allA1 = new List<A1>();
 foreach (A item in retrievedListOfA)
 {      
     allA1.Add((A1)item); 
 }

As I don't get any compile errors I find it strange that I get this error. if I do a check of the type "A is A1" then it never goes in that if statement.

Can someone point out to me why this is creating problems? Is it because object A is from a web service?

:オブジェクトをあるオブジェクトから別のオブジェクトに「移植」するこの方法がまったくばかげている場合は、どのように行うべきかを教えてください。このような試みは初めてです。

4

2 に答える 2

2

(A1)item はコンパイラに言っているので、コンパイル エラーは発生しません。

したがって、 retrieveListOfA が As と A1 のコレクションである場合、A1 にキャストするすべての A (実際には A であり、次に A1 メソッドを呼び出すと爆発します)。

コンバーターなど、多くの移植方法がありますが、キャストはその 1 つではありません。

于 2013-07-18T16:24:32.730 に答える