从类型 Object 转换匿名类型

JGi*_*tin 4 .net c# generics memorycache

我正在尝试使用 .NET 4.0 中的 System.Runtime.Caching.MemoryCache 类。我有一个通用的方法,因此我可以将任何类型传递到内存缓存中,并在调用时将其取回。

该方法返回一个 object 类型的对象,该对象是具有包含缓存对象的字段 Value 的匿名类型。

我的问题是,如何将要返回的对象转换为其相应的类型?

下面是我的代码...

public static class ObjectCache
{
    private static MemoryCache _cache = new MemoryCache("GetAllMakes");

    public static object GetItem(string key)
    {
        return AddOrGetExisting(key, () => InitialiseItem(key));
    }

    private static T AddOrGetExisting<T>(string key, Func<T> valueFactory)
    {
        var newValue = new Lazy<T>(valueFactory);
        var oldValue = _cache.AddOrGetExisting(key, newValue, new CacheItemPolicy()) as Lazy<T>;

        try
        {
            return (oldValue ?? newValue).Value;
        }
        catch
        {
            _cache.Remove(key);
            throw;
        }
    }

    /// <summary>
    /// How can i access Value and cast to type "List<IBrowseStockVehicle>"
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    private static object InitialiseItem(string key)
    {
        // SearchVehicleData.GetAllMakes(false) is of type List<IBrowseStockVehicle>
        return new { Value = SearchVehicleData.GetAllMakes(false) };
    }
}
Run Code Online (Sandbox Code Playgroud)

和单元测试...

    [TestMethod]
    public void TestGetAllMakes_Cached()
    {
        dynamic ReturnObj = ObjectCache.GetItem("GetAllMakes");

        // *********************************************
        // cannot do this as tester is of type Object and doesnt have teh field Value
        foreach(IBrowseStockVehicle item in ReturnObj.Value)
        {

        }
    }
Run Code Online (Sandbox Code Playgroud)

Pat*_*man 5

你不能。匿名类型是...匿名。它们没有您可以使用的类型名称,因此请改用类型。

当然,您仍然可以使用 Reflection,但在这种情况下可能无法真正使用:

var x = ReturnObj.GetType().GetProperty("Value").GetValue(ReturnObj);
Run Code Online (Sandbox Code Playgroud)