How can I cast a object obtained by deserialization into a type that is specified as the method parameter
public Base GetDerived(MemoryStream stream, Type type)
{
var obj = deserialzer.Deserialize(stream) ;
// return obj as type
}
where:
Class Derived: Base {}
and type argument would be typeof(Derived)
Instead of passing it is as a parameter, you can do the following
public T GetDerived<T>(MemoryStream stream) where T : Base
{
var obj = (T)deserialzer.Deserialize(stream);
// return obj as type
}
called via
var serialized = obj.GetDerived<MyClass>(stream);
You can read more about generic methods on msdn
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.