I have a static class for deserialization which should be only accessible to some of the class because only these class instance can be deserialized from the xml files and casted into that class type.
public static class Deserializer()
{
public static T deserialize<T>(string path) // T should be the classes that can do deserialization
{
// do deserialization
return (T)(deserializedObject)
}
}
public class CanDoDeserialization()
{
// class properties and methods
}
public class CannotDoDeserialization()
{
// class properties and methods
}
public class Program
{
public void Main()
{
CanDoDeserialization canInstance = new CanDoDeserialization()
canInstance = Deserializer.deserialize(somePath) //this should be okay
CannotDoDeserialization cannotInstance = new CannotDoDeserialization()
cannotInstance = Deserializer.deserialize(somePath) // this should raise compilation error
}
}
But I do not know how to implement this. Using generic deserializing method as above raises the error of "The type arguments for method ‘deserialize’ cannot be inferred from the usage. Try specifying the type arguments explicitly." I have read about interface but it seems that it can only limit those classes which implement the interface but not others that do not? And letting the CanDoDeserialization class inherit from Deserializer also sounds not right, let alone inheritance from static class is prohibited.
Very much appreciated if anyone can give some hints on this. Thank you.
Supplmentary information:
The code above is a simplied version. I want a general solution if let’s say I have 10 classes that can do deserialization and 10 that cannot. What is the best approach to generalize this deserialization method that can be implemented by these 10 classes (or even more)?
>Solution :
The classes that can be serialized should have a common interface (e.g. ISerializable):
public interface ISerializable { }
public class CanDoDeserialization : ISerializable
{
// class properties and methods
}
public class CannotDoDeserialization
{
// class properties and methods
}
You should add this interface as a constraint to your generic Type T:
public static class Deserializer
{
public static T deserialize<T>(string path) where T : ISerializable
{
// do deserialization
return (T)(deserializedObject)
}
}
This will compile:
Deserializer.deserialize<CanDoDeserialization>("path");
This won’t compile:
Deserializer.deserialize<CannotDoDeserialization>("path");
Online-demo: https://dotnetfiddle.net/7jAHJN