[nem-en] casting operators
Ivan Lakhturov
lakhturov at gmail.com
Fri Dec 15 12:34:00 CET 2006
Hello devel-en,
there is a bunch of problems with casting operators
let's start from this kind of problem:
cast operators are not visible from outside of nemerle-assembly
code for playing with:
nemerle-code:
namespace BothOverloadsDefined
{
public class A
{
public override ToString() : string
{
"instance of A"
}
}
public class B : A
{
//public static @:(_ : A) : B
//{
//System.Console.WriteLine("called A : B implicit cast");
//B()
//}
//
public static @:>(_ : A) : B
{
System.Console.WriteLine("called A :> B explicit cast");
B()
}
public static @:>(_ : int) : B
{
System.Console.WriteLine("called int :> B explicit cast");
B()
}
public override ToString() : string
{
"instance of A"
}
static Main() : void
{
//def a = A();
//def b : B = a :> B;
}
}
}
csharp code (add reference on nemerle-code that is above):
using System;
using BothOverloadsDefined;
namespace ConsumeBothOverloadsInCSharp
{
class Ancestor
{
}
class ClassDefinesImplicitCast : Ancestor
{
public static implicit operator ClassDefinesImplicitCast(int n)
{
return new ClassDefinesImplicitCast();
}
}
//class ClassDefinesExplicitCast : Ancestor
//{
// public static explicit operator ClassDefinesExplicitCast(Ancestor ancestor)
// {
// return new ClassDefinesExplicitCast();
// }
//}
class Some
{
static void Main()
{
A a = new A();
Console.WriteLine(a);
B b = new B();
Console.WriteLine(b);
//b = a; // error CS0266: Cannot implicitly convert type 'BothOverloadsDefined.A' to 'BothOverloadsDefined.B'. An explicit conversion exists (are you missing a cast?)
try
{
// System.InvalidCastException: Unable to cast object of type 'BothOverloadsDefined.A' to type 'BothOverloadsDefined.B'.
b = (B)a;
}
catch (Exception e)
{
Console.WriteLine(e);
}
Console.ReadKey();
}
}
}
compile and see under reflector what is there:
nemerle-defined casts are just public static methods, they don't
have special attribute to show the external assemblies that they are
actually casts
nemerle-decompiled code:
c#:
public static B op_Explicit(int _N_u1151);
il:
.method public hidebysig static BothOverloadsDefined.B op_Explicit(int32 _N_u1151) cil managed
c#-decompiled code:
c#:
public static implicit operator ClassDefinesImplicitCast(int n);
il:
.method public hidebysig specialname static ConsumeBothOverloadsInCSharp.ClassDefinesImplicitCast op_Implicit(int32 n) cil managed
there is no "specialname" attribute on nemerle-defined casts, so
they're invisible from the c# consumer assembly
regards, phantom
More information about the devel-en
mailing list