Find out if an instance of a DataContract is serializable in WCF

I read a man page about which types are serialized by WCF, and it is ambiguous, which types are automatically KnownType and aren't they, Can anyone shed some light on this? For example, if my DataContract has a member of type Object, it will serialize fine if I pass a string, but not if I pass a dictionary. The dictionary will require KnownType, although it is referred to as being supported on this page. I have two questions:

  • So, the question is, what are the automatic laptops that WCF always uses?

  • I need code that will determine if an instance of a KnownType object is by default. One solution would be to get an exhaustive list from the answer at 1 and check the object against each using the "obj is type" operator, but that looks bad. Is there a smarter way?

EDIT:

This link lists the types that are known by default. All primitives are less than DateTimeOffset plus XmlElement. So there are only two left: how do you know if an object is a primitive type?

EDIT 2: typeof (obj) .IsPrimitive will do most of the work!

+3
source share
1 answer

, , . :

[OperationContract]
BaseClass Foo();

:

public Foo()
{
    return DerivedClass();
}

DerivedClass BaseClass. BaseClass:

[KnownType(typeof(DerivedClass))]
[DataContract]
public class BaseClass { }

[ServiceKnownType] :

[ServiceContract]
[ServiceKnownType(typeof(DerivedClass))]
public interface IService
{
    [OperationContract]
    BaseClass Foo();
}

:

<system.runtime.serialization>
    <dataContractSerializer>
        <declaredTypes>
            <add type="SomeNs.BaseClass, SomeAssembly">
                <knownType type="SomeNs.DerivedClass, SomeAssembly"/>
            </add>
        </declaredTypes>
    </dataContractSerializer>
</system.runtime.serialization>

UPDATE:

, :

, .NET Framework : , SByte, Int16, Int32, Int64, UInt16, UInt32, UInt64, Single, Double, Boolean, Char, Decimal, Object String.

+1

Source: https://habr.com/ru/post/1778520/


All Articles