开发者

Visual Studio: Detect type presence in a container

开发者 https://www.devze.com 2023-01-28 21:08 出处:网络
I have the following situation: I do serialization of an object: MyBOContainer. It throws me serialization errors \"the class MyUIElement is not marked as serializable\".

I have the following situation: I do serialization of an object: MyBOContainer.

It throws me serialization errors "the class MyUIElement is not marked as serializable".

Normally, I shouldn't have such a class between myBOContainer elements(or their children). However, I have some public List<object> and theoretically this is possible.

Question:

How can I test in the Debug Mode in VS if an instance of object myBOCo开发者_如何学JAVAntainer contains(deepsearch) or not instances of MyQueryTestClass type?


If you can't predict what the data is, then IMO you shouldn't be serializing that element.

Since it appears you are using BinaryFormatter, perhaps add some [NonSerialized]:

[NonSerialized]
private List<object> foo = ...

Also, events are the usual cause of confusion on this; I would annotate any events, too:

[field:NonSerialized]
public event EventHandler SomeCrazyEvent;

or if you are doing explicit event implementations, set [NonSerialized] on whatever backing field is holding the delegate or EventHandlerList.

(well, strictly speaking I just wouldn't be using BinaryFormatter in the first place - using a serialize that isn't so tied to the internal class structure can only be a good thing; but that is a rant for another day...)


So, the solution that worked was to activate the .NET Framework code debug mode. Then, from the exception stack trace find the function that throw the exception and debug step by step.

Identifying the moment that the exception was thrown I found out that the "alien" who introduced me UserControls in the BO class was the Event, that was used by the UserControl.

Solution - make this event as [NonSerialized].


How can I test in the Debug Mode in VS if an instance of object myBOContainer contains(deepsearch) or not instances of MyQueryTestClass type?

Here is some C# code that does exactly this:

if (myBOContainer.OfType<MyQueryTestClass>().Any())
{
    // the container contains an item of type MyQueryTestClass
}

So if you have a List<object>, then either don't serialize it (use NonSerializedAttribute like the others said), or simply remove the items that are not serializable.

myList.RemoveAll(myList.OfType<MyNonSerializableClass>());

Or perhaps use reflection to see which item is serializable.

My recommended solution

Never ever use a List<object> to store random objects. This is usually caused by disregarding strongly-typedness which is always bad in a strongly typed language. Use List<SomeSpecificType> instead.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号