我有一些WebApi控制器,我想从中获取数据。我有各种各样的DTO,我想拥有一个能够处理所有DTO的功能。 有办法吗?
我想要实现以下目标:
public dynamic GetData(string ControllersName, dynamic DTOType)
{
string Url = Settings.baseURLAddress + ControllersName;
var request = (HttpWebRequest)HttpWebRequest.Create(Url);
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<DTOType>));
var response = (List<DTOType>)serializer.ReadObject(request.GetResponse().GetResponseStream());
return response;
}
答案 0 :(得分:4)
您是否尝试过使用泛型?
public List<T> GetData<T>(string ControllersName, T DTOType)
{
string Url = Settings.baseURLAddress + ControllersName;
var request = (HttpWebRequest)HttpWebRequest.Create(Url);
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<T>));
var response = (List<T>)serializer.ReadObject(request.GetResponse().GetResponseStream());
return response;
}
答案 1 :(得分:1)
您可以泛型
public List<T> GetData<T>(string ControllersName)
{
string Url = Settings.baseURLAddress + ControllersName;
var request = (HttpWebRequest)HttpWebRequest.Create(Url);
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<T>));
return (List<T>)serializer.ReadObject(request.GetResponse().GetResponseStream());
}
用法
var myList = GetData<SomeType>(someName);
进一步阅读
Generics (C# Programming Guide)
泛型向.NET Framework引入了类型的概念 参数,从而可以设计出以下类和方法 将一种或多种类型的规范推迟到类或方法之前 由客户端代码声明和实例化。