c# - C# - 匹配类型和值的最有效方式
问题描述
我正在开发 EVE Online 应用程序。EVE API 提供了很多不同的数据,我想为所有这些数据编写通用方法。
我的想法是编写通用方法,从传递的类型中“提取”到 API 的路径并发送适当的请求。例如:
interface ICommonResponse
{
//some method or property
}
class FwLeaderboards : ICommonResponse
{
//some fields corresponding to api response
}
public T Get<T>() where T : ICommonResponse
{
string path = SomeMagic(T); //we "extract" path from type
return Send<T>(path); //this method retrieves JSON string from api and deserializes it to object of FwLeaderboards type
}
如何提取路径?不幸的是,直接调用静态成员是非法的T
。所以,我看到了三种方式。
反射
abstract class CommonResponse
{
public static string Path() => null;
}
class FwLeaderboards : CommonResponse
{
new public static string Path() => "/fw/leaderboards/";
//some fields corresponding to api response
}
public T Get<T>() where T : CommonResponse
{
string path = (string)typeof(T).GetMethod("Path").Invoke(null,null);
return Send<T>(path);
}
实例化
我们创建一个类的实例并调用方法。
interface ICommonResponse
{
string Path() => null;
}
class FwLeaderboards : ICommonResponse
{
public override string Path() => "/fw/leaderboards/";
//some fields corresponding to api response
}
public T Get<T>() where T : ICommonResponse, new()
{
T val = new T();
return Send<T>(val.Path());
}
字典
我们有一个Dictionary
(或任何其他集合)Type
作为键。
IDictionary<Type, string> dict = ...;//Initialize dictionary
interface ICommonResponse
{
}
class FwLeaderboards : ICommonResponse
{
//some fields corresponding to api response
}
public T Get<T>() where T : ICommonResponse
{
var path = dict[typeof(T)]; //returns "/fw/leaderboards/" for FwLeaderboards
return Send<T>(val.Path());
}
那么,最有效的方法是什么?
解决方案
推荐阅读
- ios - 与控制中心相同的当前 ViewController 在 iPhone 中工作
- javascript - 编辑条目时电子应用程序不更新条目
- ruby-on-rails - Rails 6 中的 Rails 红色开发错误页面在哪里?
- go - 如何在for-select循环中更改频道
- javascript - Javascript Fetch 没有服务器消息
- angular - 需要帮助才能使用 Orange Money 的 API
- javascript - React native 无需权限即可访问相机或照片库
- c# - C# xamarin 表单中文件夹中的文件名?[安卓]
- python - 导入 ModuleNotFoundError:运行 sagemaker 管道步骤时没有名为 X 的模块
- angular - 如何使用 Angular 6 进行多个独立订阅?