C #: Superclass still has subclass information after upcast

I have 2 types: BaseQuestionand Question. Questioninherits some properties from BaseQuestion. Now I have created a web API to make it BaseQuestionaccessible. The data type Questionhas additional properties that I do not want to provide. I have a method that extracts Question, and my original plan was to simply implicitly increase it to BaseQuestion. I thought that he would lose all the additional properties that I do not want to make available, and I could return it. Well, that is not so. This is what I do:

Question q = allQuestions[0];
BaseQuestion bq = q;
string type = bq.GetType().ToString();

Type bq is still a "Question". I cannot access the BaseQuestion properties, but I still see them in the debugger, and they are in the JSON output that I send to the client.

Any ideas on how I can make bq be type BaseQuestionand not have any properties defined in a subclass?

+5
source share
2 answers

Typecasting does not change the nature of the object, it only changes your idea of ​​the object. When you assign a type to a base type, you view the object through a filter that can only see elements defined in the base type, regardless of what else is defined in the actual object.

When you return an object from a web service call, this is the actual object that will be serialized and sent back through the wire - all of its serializable elements.

, , Question API-, , Question. .NET , XmlSerialization, , Question [XmlIgnore], XmlSerialization. , .

-API-. BaseQuestion Question . , , , , .

, BaseQuestion temp var, Question temp temp. , , .

+11

Typecasting , .

.GetType() Question Question , .

, .BaseType .

, - :

string type = q.GetType().BaseType.ToString();
+1

All Articles