The reason the cast doesn't work is because Parse()
returns a JObject
. Even though Parse()
is available on your specialized JObject
named JObjectTotalJiraTickets
, this does not mean it will suddenly return a JObjectTotalJiraTickets
instead of a JObject
.
Possible fix
You could create a new Parse()
method that replaces the original one like so:
public class JObjectTotalJiraTickets : JObject
{
public static new JObjectTotalJiraTickets Parse(string json)
{
// Re-use base class parse logic.
var jobj = JObject.Parse(json);
// Your logic to create a `JObjectTotalJiraTickets` from a `JObject`.
JObjectTotalJiraTickets myjobj = DoTheJiraThings(jobj)
return myjobj;
}
}
Note the new
modifier that replaces the inherited Parse()
method.
In fact, if you look at the source of JObject
, you will find that it does exactly that to replace/extend the parse logic it inherited from JToken
.
Avoid inheritance
Be aware though that inheritance is almost always the worst way to go. Try to avoid it if possible and look for a different approach.
"But still... why does the cast not work?"
The compiler is trying to tell you that it makes no sense to assume that every JObject
is also always a JObjectTotalJiraTickets
. That's like saying every Animal
is always a Cat
. It's not only false, it's also offensive to cats.
The other way around, however, makes sense: JObject o = new JObjectTotalJiraTickets()
which is like saying every Cat
is an Animal
.
With the explicit cast JObjectTotalJiraTickets o = (JObjectTotalJiraTickets)new JObject()
you are effectively telling the compiler that you know better and you are 100% sure the JObject
instance actually is a JObjectTotalJiraTickets
. The compiler will believe you, but the cast will fail at runtime.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…