El error "La conversión definida por el usuario debe convertirse ao desde el tipo adjunto" dice exactamente lo que significa. Si usted tiene un operador de conversión
class MyClass {
public static explicit operator xxx(string s) { // details }
public static implicit operator string(xxx x) { // details }
}
Entonces xxx
debe haber MyClass
. Esto es lo que significa "la conversión debe convertirse hacia o desde el tipo adjunto". El tipo adjunto aquí es MyClass
.
La sección correspondiente de la # especificaciones ECMA334 C es 17.9.4:
A conversion operator converts from a source type, indicated by the parameter type of the conversion operator, to a target type, indicated by the return type of the conversion operator. A class or struct is permitted to declare a conversion from a source type S to a target type T only if all of the following are true, where S0 and T0 are the types that result from removing the trailing ? modifiers, if any, from S and T:
S0 and T0 are different types.
Either S0 or T0 is the class or struct type in which the operator declaration takes place.
Neither S0 nor T0 is an interface-type.
Excluding user-defined conversions, a conversion does not exist from S to T or from T to S.
Así que aquí está el código:
public static explicit operator List<Model.objA>(List<Entity.objA> entities) {
List<Model.objA> objs= new List<Model.objA>();
foreach (Entity.objA entity in entities) {
objs.Add((Model.objA)entity);
}
return claims;
}
El tema es que para que esto se define como un operador de conversión que debe residir en las clases List<Model.objA>
o List<Entity.objA>
pero, por supuesto, no puede hacer eso ya que no tiene acceso para cambiar esos tipos.
Puede usar Enumerable.Select
para proyectar al otro tipo o List<T>.ConvertAll
. Por ejemplo:
public static class ListExtensions {
public static List<Model.objA> ConvertToModel(this List<Entity.objA> entities) {
return entities.ConvertAll(e => (Model.objA)e);
}
}