When implicit type conversion is performed, the error message "user-defined conversion must be converted to a closed type or from a closed type" is returned ":
The statement is roughly as follows:
There are two classes: A and B, where Class A and Class B have the same structure, but class B belongs to A third party;
In A method of class C, you need to return A List <A>, for example:
[Csharp]
Public List <A> Func ()
{
List <B> list = new List <B>;
.....
Return list;
}
Public List <A> Func ()
{
List <B> list = new List <B>;
.....
Return list;
}
In this case, an error is reported because the return type is different;
Implicit conversions in Class
[Csharp]
Class
{
....
Public static implicit operator List <A> (List <B> value)
{
...
}
.....
}
Class
{
....
Public static implicit operator List <A> (List <B> value)
{
...
}
.....
} At this time, the error "user-defined conversion must be converted to a closed type or from a closed type conversion" will be reported;
Refer to MSDN and see the following two descriptions in the "type conversion" section:
1. the operand must be of the closed type.
2. The conversions between Class A and Class B cannot be defined in class C (that is, the conversions between two classes cannot be defined in 3rd classes)
At first, I thought it was the cause of the first compilation error. I also mistakenly thought that the so-called closed type must be a class/structure and cannot be a collection object, later I found that the cause of this error is the second point, because when I change the definition of type conversion:
[Csharp]
Class
{
....
Public static implicit operator A (List <B> value)
{
...
}
.....
}
Class
{
....
Public static implicit operator A (List <B> value)
{
...
}
.....
}
After compilation, the first point is excluded;
Originally, for the compiler, class A is A type, List <A> is also A type, and List <B> is also A type, therefore, operations of the List <B> type implicitly converted to the List <A> type cannot be performed in class A, which conforms to the second point;
Supplement:
To be in a project, you can:
[Csharp]
Public List <A> Func ()
{
List <B> list = new List <B>;
.....
Return list;
}
Public List <A> Func ()
{
List <B> list = new List <B>;
.....
Return list;
}
How to convert the list to List <A>?
In fact, the method is also very simple. Since the implicit conversion of List <T> cannot be done, you can convert the elements in list one by one when returning:
Implicit conversion definition:
[Csharp]
Class
{
....
Public static implicit operator A (B value)
{
...
}
.....
}
Class
{
....
Public static implicit operator A (B value)
{
...
}
.....
}
Method definition:
[Csharp]
Public List <A> Func ()
{
List <B> list = new List <B>;
.....
Return list. Select (p => (B) p). ToList ();
}
Public List <A> Func ()
{
List <B> list = new List <B>;
.....
Return list. Select (p => (B) p). ToList ();
}
I would like to share this with my friends who have encountered the same problem and do not know why.