首页 > 解决方案 > 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());
}

那么,最有效的方法是什么?

标签: c#genericstypes.net-core

解决方案


推荐阅读