[KnownTypeAttribute(Type type)]
[KnownTypeAttribute(string typeName)]
public sealed class KnownTypeAttribute : Attribute
The KnownTypeAttribute attribute is used in .NET serialization to inform the serializer about types that might not be discoverable through reflection alone. This is particularly useful when dealing with polymorphism, abstract classes, or interfaces where the runtime type of an object being serialized or deserialized might be different from its declared type.
When a class is marked with KnownTypeAttribute, the serializer will include the specified type in its list of types that it can handle. This helps prevent runtime errors during deserialization, such as SerializationException, which can occur if the serializer encounters a type it doesn't recognize.
The attribute can be applied multiple times to a class to specify several known types.
| Constructor | Description |
|---|---|
| KnownTypeAttribute(Type type) | Initializes a new instance of the KnownTypeAttribute class with the specified type. |
| KnownTypeAttribute(string typeName) | Initializes a new instance of the KnownTypeAttribute class with the specified type name. The serializer will attempt to resolve this type name at runtime. |
This example demonstrates how to use the KnownTypeAttribute to specify known types for serialization of a base class.
using System;
using System.Runtime.Serialization;
[KnownType(typeof(Dog))]
[KnownType(typeof(Cat))]
public abstract class Animal
{
public abstract string Speak();
}
public class Dog : Animal
{
public override string Speak()
{
return "Woof!";
}
}
public class Cat : Animal
{
public override string Speak()
{
return "Meow!";
}
}
// Example usage (serialization/deserialization logic would be here)
public class SerializationExample
{
public static void Main(string[] args)
{
Animal myDog = new Dog();
Animal myCat = new Cat();
// In a real scenario, you would use a serializer like DataContractSerializer
// or XmlSerializer to serialize myDog and myCat.
// The KnownTypeAttribute ensures that Dog and Cat types are recognized.
Console.WriteLine($"Dog speaks: {myDog.Speak()}");
Console.WriteLine($"Cat speaks: {myCat.Speak()}");
}
}
This example shows how to specify known types using their string names.
using System;
using System.Runtime.Serialization;
[KnownType("MyNamespace.MyDerivedClass1, MyAssembly")]
[KnownType("MyNamespace.MyDerivedClass2, MyAssembly")]
public abstract class MyBaseClass
{
// ... members
}
// Assume MyDerivedClass1 and MyDerivedClass2 are defined elsewhere
// in MyNamespace and MyAssembly.
// Example usage:
public class AnotherSerializationExample
{
// Serialization/deserialization logic would use these known types.
}