Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用反射获取类型以馈送到泛型类_C#_Reflection - Fatal编程技术网

C# 使用反射获取类型以馈送到泛型类

C# 使用反射获取类型以馈送到泛型类,c#,reflection,C#,Reflection,如何使用类名字符串获取类名/类型?像 Dictionary<string, string> DFields = GetFields(); Dictionary-DFields=GetFields(); 类型是 Dictionary<string, string> object = Deserialize<?>(_stream) 字典 对象=反序列化(\u流) 理想情况下,我在想: object = Deserialize<"Dictionary&

如何使用类名字符串获取类名/类型?像

Dictionary<string, string> DFields = GetFields();
Dictionary-DFields=GetFields();
类型是

Dictionary<string, string>
object = Deserialize<?>(_stream)
字典
对象=反序列化(\u流)
理想情况下,我在想:

object = Deserialize<"Dictionary<string, string>">(_stream)
object=反序列化(\u流)
它应该成为

object = Deserialize<Dictionary<string, string>>(_stream) 
object=反序列化(\u流)

为了工作。我序列化了10个对象,但是我只有字符串格式的类型名。我需要将字符串格式格式化为实际类型,以便将其提供给通用序列化程序反序列化程序函数。

步骤1-获取类型实例:

var genericMethod = typeof(Serialzier).GetMethod( "Deserializer" );
var parametizedMethod = genericMethod.MakeGenericMethod( type );
var parameters = new object[] { _stream };
var deserializedInstance = parametizedMethod.Invoke( null, parameters );
您需要使用传递到
Type.GetType()
中的程序集限定名。 通过在Dictionary()类型实例上调用
GetType().AssemblyQualifiedName
进行快速测试,结果是:

System.Collections.Generic.Dictionary`2[[System.String,mscorlib,Version=4.0.0,Culture=中性,PublicKeyToken=b77a5c561934e089],[System.String,mscorlib,Version=4.0.0.0,Culture=中性,PublicKeyToken=b77a5c561934e089],mscorlib,Version=4.0.0.0,Culture=中性,PublicKeyToken=b77a5c561934e089]

一团糟。我相信您可以删除大部分,但它仍然有效:

System.Collections.Generic.Dictionary`2[[System.String,mscorlib],[System.String,mscorlib]],mscorlib

因此:

var typeName = "System.Collections.Generic.Dictionary`2[[System.String, mscorlib],[System.String, mscorlib]], mscorlib";
var type = Type.GetType( typeName );
步骤2(假设API强制使用IMO为SHOT的泛型参数)-使用反射动态参数化泛型方法:

var genericMethod = typeof(Serialzier).GetMethod( "Deserializer" );
var parametizedMethod = genericMethod.MakeGenericMethod( type );
var parameters = new object[] { _stream };
var deserializedInstance = parametizedMethod.Invoke( null, parameters );

没有。我只有像“Dictionary”这样的字符串作为Dictionary。我需要将这个字符串转换为像Dictionary这样的实际类型。它应该变成字符串类型到实际的实数类型;它说:运算符“此Protobuff网络反序列化程序只有方法:反序列化程序()。没有其他反序列化方法。我必须将此字符串类型提供给T。我不熟悉Protobuff net,但快速查看一下该序列化程序类,它在内部所做的只是:
return(T)RuntimeTypeModel.Default.Deserialize(source,null,typeof(T))。假设
RuntimeTypeModel
是公共的,希望类似的东西能起作用:
object=RuntimeTypeModel.Default.Deserialize(_stream,null,type)。好的,它可以工作。谢谢。当我看到泛型时,我会记住这个技巧。