|
simple...
your custom operators are only design to take a string or int, so you can only cast with those values. object is of type 'object'.
you could create an operator for 'object'...
public static explicit operator MyCar(object o)
{
if(o is string)
return new MyCar((string)o);
if(0 is int)
return new MyCar((int)o);
}
Life goes very fast. Tomorrow, today is already yesterday.
|
|
|
|
|
The first thing I thought of too but I get
user-defined conversions to or from a base class are not allowed
DaveBTW, in software, hope and pray is not a viable strategy. (Luc Pattyn) Visual Basic is not used by normal people so we're not covering it here. (Uncyclopedia) Why are you using VB6? Do you hate yourself? (Christian Graus)
|
|
|
|
|
that's strange as im sure i have used the same functionality before, hold on....
oh no, that was different (not casting).
perhaps then a static function would be the way forward. surely that would work
Life goes very fast. Tomorrow, today is already yesterday.
|
|
|
|
|
Check the type in the GetMyCar and cast as needed:
private static MyCar GetMyCar(object car)
{
if (car is string)
{
return (MyCar)((string)car);
}
else if (car is int)
{
return (MyCar)((int)car);
}
else if (car is MyCar)
{
return (MyCar)car;
}
throw new ArgumentException("Object must be MyCar, string or int.");
}
DaveBTW, in software, hope and pray is not a viable strategy. (Luc Pattyn) Visual Basic is not used by normal people so we're not covering it here. (Uncyclopedia) Why are you using VB6? Do you hate yourself? (Christian Graus)
|
|
|
|
|
I have thought of this, but the real world application (which I cannot post code from) doesn't allow this. (it doesn't have a "GetMyCar" function) This code sample was an attempt to demonstrate my real problem.
Basically, I have a datareader that stores all of it's values into an object array. One of these values are of type "int". I have generic code that takes the int object and loads it into a specific type. Casting it works on the standard .Net types but does not work on custom classes, like "MyCar" in the example.
object o= value;
MyCar car = (MyCar)o;
I guess I could right similar code here, like MyCar.CanConvertFrom() (using IConvertible) and then cast the value to int then do the explicit conversion. I was hoping I could do this in the MyCar class instead.
|
|
|
|
|
Hi,
Int or String is not a MyCar and the cast attempted in the GetMyCar will always fail.
GetMyCar should create an object of type MyCar by invoking the appropriate constructor based on the type of the parameter.
Alan.
[EDIT] I may have misunderstood your operators which I find terminally confusing!
|
|
|
|
|
The above posts should give you a way to make your code do what you seem to be asking. For a fuller description of why your code will not work as written, I recommend this article that talks about the question you are asking. To quote from about half-way down:
Eric Lippert wrote: All that the compiler knows is that [your object] is of type object. It could be anything. Suppose it is a boxed int – then the compiler should generate an unboxing instruction. Suppose it is a boxed short. Then the compiler should unbox the short and then generate the custom sequence of instructions that convert a short to an int. Suppose it is a boxed double – same thing, but different instructions. And so on, for all the built-in conversions that go to integer.
Basically, when you have this line of code:
MyCar theCar = (MyCar)carObj;
The compiler says, "The programmer assures me that this object is actually an instance of the derived class MyCar, so I will double-check to make sure when I assign it and throw an InvalidCastException if its not."
In this case:
MyCar theCar3 = (MyCar)(string)carObj;
You tell the compiler carObj is a string then tell it to convert to an unrelated class MyCar. At that point, the compiler looks for a conversion operator (which it finds) and emits the call to your custom method.
|
|
|
|
|
|
Using the code in that article, I came up with a modified version fo GetMethod and DynamicCast:
public static MethodInfo GetMethod(Type toSearch, string methodName, Type inputType, BindingFlags bindingFlags)
{
return Array.Find(toSearch.GetMethods(bindingFlags),
delegate(System.Reflection.MethodInfo inf) {
return ((inf.Name == methodName) && (inf.ReturnType == toSearch) && inf.GetParameters().Length == 1 && inf.GetParameters()[0].ParameterType == inputType); });
}
public static T DynamicCast<T>(object o)
{
Type objectType = o.GetType();
Type returnType = typeof(T);
MethodInfo meth = GetMethod(returnType, "op_Implicit", objectType, BindingFlags.Static | BindingFlags.Public);
if (meth == null)
{
meth = GetMethod(returnType, "op_Explicit", objectType, BindingFlags.Static | BindingFlags.Public);
}
if (meth == null)
throw new InvalidCastException("Invalid Cast.");
return (T)meth.Invoke(null, new object[] { o });
}
This seems to work, may need a little more testing. I'm not sure how this will affect performance.
|
|
|
|
|
You are essentially resolving the operator overload at run time, instead of compile time. You might want to lookup the overload resolution rules though - your current implementation of GetMethod will fail if the operand's type is a subtype of the parameter type, for example. And return types are not involved in overload resolution as well.
|
|
|
|
|
I try to write service using C#.
After i done i install the assembly using InstallUtil.exe
Now, the assemble exe is running but i cant stop/start this service from the windows services.
How can i control the process from the windows services ?
|
|
|
|
|
use try-catch in OnStart and OnStop, write the error message to a file or eventLog.
|
|
|
|
|
use System.ServiceProcess.ServiceController class.
sample code:
System.ServiceProcess.ServiceController serviceController = new System.ServiceProcess.ServiceController();
serviceController.ServiceName = "MyService";
serviceController.Start();
serviceController.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Running);
serviceController.Stop();
serviceController.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Stopped);
Ala'a Al Atrash
Globitel.
Khalda - Amman - Jordan
Software Developer
Mobile Tel:- +962 79 030141
|
|
|
|
|
Hi,
to my c#.net 3.5 application i added a setup project. setup created successfully and running fine.
but when am trying to install in a computer where there is no .net 3.5 framework it is asking in window that 'This setup requires the .NET framework 3.5. please install .net framework and run this setup again. The .NET Framework can be obtained from the web. Would you like to do this now?' with Yes and No buttons.
but in my setup project Prequisites property i selected .Net freamework2.0, 3.5 and window installer 3.1
and i selected 2nd radiobutton that is Download prerequisites from the same location as my application.
i build it successfully i got respective folders in to my debug folder.
but during the installation it is not installing automatically that .net framework3.5
forcefully am going to install framework.
To install automatically what i have to do?
Please explain.
Thanks in advance.
--Naren
|
|
|
|
|
Please stop cross-posting your questions.
Henry Minute
Do not read medical books! You could die of a misprint. - Mark Twain
Girl: (staring) "Why do you need an icy cucumber?"
“I want to report a fraud. The government is lying to us all.”
|
|
|
|
|
sorry, am in hurry for the answer so i did unexpectdly. please dont mind.
|
|
|
|
|
I have a text file which, is basically being used as a database in my project.
My program reads the file, makes some changes then saves it again.
I have the program working fine, except that it explicitly reference the text file by its path and name.
The problem is I now want to publish the program for others to use.
I want the text file to be included in the publish and I want the program to use that file given.
As it stands, because I have hard coded the path to the file. The program won't work on any other machine.
How do I;
1.) Have the text file included when people run my publish instalation file.
2.) Let the program know where to get the file.
|
|
|
|
|
You probably want the file to reside in the same path as the exe file.
1 simply include the file in the project and make sure your deployment project includes it.
2 check out the application.exepath or the assembly.startlocation (there are a number of references to the folder you want).
Never underestimate the power of human stupidity
RAH
|
|
|
|
|
You could use the project's Resources component to house the file.
|
|
|
|
|
I an writing a new "language" of programming
the user uses the new "language" and then it is beeing translated ino c# in rich-text-box
how do I execute this string?
I am begginer and I am looking for simple example or this
Is there any?
|
|
|
|
|
Are you going to create a new programming language? Please don't mind but can you ellaborate more on what are you going to do.
Either you love IT or leave IT...
|
|
|
|
|
You must be doing the same course as another twit in the forums, asked the same questions and didn't understand the answers.
Try searching recent posts you should be able to find it!
Never underestimate the power of human stupidity
RAH
|
|
|
|
|
I have a feeling that this is the same twit.
Henry Minute
Do not read medical books! You could die of a misprint. - Mark Twain
Girl: (staring) "Why do you need an icy cucumber?"
“I want to report a fraud. The government is lying to us all.”
|
|
|
|
|
rachelicohen wrote: I am begginer
So writing what is effectivley a compiler is going to be way outside your capabilities. Get a good book on C#, start at the beginning and learn to walk before you run.
Bob
Ashfield Consultants Ltd
Proud to be a 2009 Code Project MVP
|
|
|
|
|
How to Improve Cellformatting event time consumtion while loading large no of rows and paint some selected cells?
Please send me an answer.
|
|
|
|