在文件中写入和读取类型值

Vil*_*men 3 c# io types

我需要能够将类型值存储到文件中,然后将其读回到类型值中.最好的方法是什么?

Type type = typeof(SomeClass);
binaryWriter.Write?(type);
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 8

我将存储程序集限定的名称,假设程序集将在以后出现:

binaryWriter.Write(type.AssemblyQualifiedName);
...
string typeName = binaryReader.ReadString();
Type type = Type.GetType(typeName);
Run Code Online (Sandbox Code Playgroud)

如果您已经知道该类型将使用哪个程序集,则可以使用全名(即名称空间和类型名称,但不能使用程序集).然后再使用Assembly.GetType(string).