المساعد الشخصي الرقمي

مشاهدة النسخة كاملة : Unboxing an unknown type



C# Programming
04-30-2009, 03:22 PM
I have a strange problem with unboxing.

Take this code:
public class MyCar
{
public string Name;
public MyCar(string name) { this.Name = name; }
public MyCar(int carNbr) { if (carNbr==1) this.Name="Honda"; else this.Name="Unknown"; }
public static explicit operator MyCar(string value)
{
return new MyCar(value);
}
public static explicit operator MyCar(int value)
{
return new MyCar(value);
}
}
private static MyCar GetMyCar(object car) // car is a boxed string or int
{
return (MyCar)car; // does not work
}
static void Main(string[] args)
{
string carName = "Honda";
object carObj = carName; // carObj is of type object with carName boxed
MyCar theCar = (MyCar)carObj; // Invalid cast
MyCar theCar2 = (MyCar)carName; // Works !
MyCar theCar3 = (MyCar)(string)carObj; // Works
MyCar theCar4 = GetMyCar((object)1); // invalid cast
MyCar theCar5 = GetMyCar(carObj); // invalid cast
MyCar theCar6 = GetMyCar(carName); // invalid cast
}


So can I get the function GetMyCar to return properly if the car type
is a string or integer? I though of doing something with Type, but couldn't find anything.

Anyone have any ideas?

Thanks in advance for your help.