I asked this question a while ago, but did not get an acceptable answer. Basically, I cannot get my method of duplicating objects to work due to invalid cast exceptions. But I can distinguish things outside of the duplication method.
Here is the duplication method
public static class ObjectDuplicator { public static T Clone<T>(T source) { if (!typeof(T).IsSerializable) { throw new ArgumentException("the Type must be serializable.", "source"); } if (Object.ReferenceEquals(source, null))
The problem is this: when I call this method using the code below
public void AddJob(Job job) { if (!Jobs.Contains(job)) { Job newcopy = Utilities.ObjectDuplicator.Clone<Job>(job); Jobs.Add(newcopy); } }
he throws this exception:
Thrown System.InvalidCastException unhandled message = cannot execute object of type 'KH.CharacterClasses.Freelancer' to type 'KH.CharacterClasses.Job'
Now the type of job that I am adding is an inherited class from Job, (Freelancer), and the code for these two classes is below
[Serializable] public class Job : Ability { protected JobCommand basecommand1; protected JobCommand basecommand2; protected JobCommand basecommand3; protected JobCommand basecommand4; protected JobCommand command1; protected JobCommand command2; protected JobCommand command3; protected JobCommand command4; bool mastered; protected FFJob job; protected string name; int level; public FFJob SetJob { get { return job; } } public bool Mastered { get { return mastered; } } public JobCommand Command1 { get { return command1; } set { command1 = value; } } public JobCommand DefaultCommand1 { get { return basecommand1; } } public JobCommand Command2 { get { return command2; } set { command2 = value; } } public JobCommand DefaultCommand2 { get { return basecommand2; } } public JobCommand Command3 { get { return command3; } set { command3 = value; } } public JobCommand DefaultCommand3 { get { return basecommand3; } } public JobCommand Command4 { get { return command4; } set { command4 = value; } } public JobCommand DefaultCommand4 { get { return basecommand4; } } public Job(string name, string description, int jobID) : base(name, description, jobID, -1, -1, null, null, -1, -1) { } public static bool operator ==(Job job1, Job job2) { if (System.Object.ReferenceEquals(job1, job2)) return true; if (((object)job1 == null) || ((object)job2 == null)) return false; return (job1.Name == job2.Name && job1.UID == job2.UID); } public static bool operator !=(Job job1, Job job2) { return !(job1 == job2); }
I really don't know what the problem is. As I said, casting works fine outside of this method, and I know that this code worked before. Any ideas?
thanks