Switch для .GetType() - C#
Формулировка задачи:
Немного экспериментирую с сериализацией, хотелось бы найти способ заменить конструкцию if ... else if...elsr if... на что нибудь более "симпатичное", чтото вроде switch и хотелось бы как то избавиться от кучи new test().GetType().
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace testbinary
{
class Program
{
static void Main(string[] args)
{
test response = new test();
response.id = 1;
MemoryStream ms = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(ms, response);
MemoryStream fs = new MemoryStream(ms.ToArray());
BinaryFormatter formatter2 = new BinaryFormatter();
object t = formatter.Deserialize(fs);
Type type = t.GetType();
if (type == new demo().GetType())
{
demo r = (demo)t;
Console.WriteLine("demo");
}
else if (type == new test().GetType())
{
test r = (test)t;
Console.WriteLine("test");
}
else
{
Console.WriteLine("-");
}
Console.ReadLine();
}
}
[Serializable]
class demo
{
public int id;
}
[Serializable]
class test
{
public int id;
}
}Решение задачи: «Switch для .GetType()»
textual
Листинг программы
var obj = (IDescribable) formatter.Deserialize(fs); Console.WriteLine(obj.Description); // "demo", "test", ... в зависимости от определения виртуального свойства