通过类的名称反射类替代泛型
ProtocolBuffersMessageDecoder类中有泛型方法DecodeMessage
public class ProtocolBuffersMessageDecoder : IMessageDecoder
{
public ProtocolBuffersMessageDecoder();
public T DecodeMessage<T>(byte[] data);
}
public interface IMessageDecoder
{
T DecodeMessage<T>(byte[] data);
}
IMessageDecoder _decoder = new ProtocolBuffersMessageDecoder();
System.Net.WebRequest wReq = System.Net.WebRequest.Create(Url);
wReq.Method = "GET";
// Get the response instance.
System.Net.WebResponse wResp = wReq.GetResponse();
System.IO.Stream stream = wResp.GetResponseStream();
byte[] body = StreamToBytes(stream);
var asm = Assembly.LoadFile(ConfigurationManager.AppSettings["FeedContractsDLLPath"]);
Type tObject = asm.GetType(ConfigurationManager.AppSettings["ReflectClassFullName"]);
MethodInfo method = typeof(IMessageDecoder).GetMethod("DecodeMessage", new Type[] { typeof(byte[])});
MethodInfo generic = method.MakeGenericMethod(tObject);
var cases = generic.Invoke(_decoder, new object[] { body });
//var cases = _decoder.DecodeMessage<CaseProfileCollection>(body);
var result = JsonConvert.SerializeObject(cases);
return result;
public static byte[] StreamToBytes(Stream stream)
{
List<byte> bytes = new List<byte>();
int temp = stream.ReadByte();
while (temp != -1)
{
bytes.Add((byte)temp);
temp = stream.ReadByte();
}
return bytes.ToArray();
}
配置
<appSettings>
<add key="url" value="http://www.baidu.com"/>
<add key="FeedContractsDLLPath" value="F:\\working\\FeedContracts.dll" />
<add key="ReflectClassFullName" value="FeedContracts.CaseProfileCollection" />
</appSettings>
FeedContracts.CaseProfileCollection为FeedContracts下的一个class
原本需要在代码中用FeedContracts显示的替代泛型可以通过配置动态进行改变