Func 参数 - 方法的类型参数无法从用法中推断出来

本文关键字:类型参数 用法 推断出 方法 TResult 参数 Func | 更新日期: 2023-09-27 18:30:46

我有以下方法

Func<string,IEnumerable<dynamic>> getLpVideos = delegate(string language)
{
    var id = GetBy(language);
    return new List();
}; 

我想将这样的参数传递给泛型方法,但我对如何在 GetObjectFromMemoryCacheWithDefParams 以及如何调用 GetObjectFromMemoryCacheWithDefParams 感到困惑:

public T GetObjectFromMemoryCacheWithDefParams<T>(
    string key, Func<string, T> defGetValueFunc) where T : class
{
    var result = _cache.Get(key) as T;
    return result ?? defGetValueFunc();//here error
}

//The type arguments for method cannot be inferred from the usage
var result = CacheService
    .GetObjectFromMemoryCacheWithDefParams(casheName, getLpVideos(lng));

仅当显式提供类型参数时,它才起作用。

Func<T, TResult> 参数 - 方法的类型参数无法从用法中推断出来

您没有按预期传入Func<string, T>。您正在传递一个IEnumerable<dynamic>,这是一个在运行时计算的动态表达式。请注意,getLpVideos(lng) 不是函数,而是函数调用,这意味着它的返回值用作第二个参数,而不是函数本身。您需要这个:

var result = CacheService
    .GetObjectFromMemoryCacheWithDefParams(casheName, getLpVideos);

此外,您需要在 GetObjectFromMemoryCacheWithDefParams 方法中修复函数调用 - 它需要一个输入参数,而您不提供该参数:

所以改变这个:

return result ?? defGetValueFunc();

对此:

return result ?? defGetValueFunc(key);

如果我正确理解您的问题,您只想让电话正常工作。 在这种情况下你只需要明确地告诉它T是什么类型。 在您的情况下,这是IEnumerable<dynamic>. 所以你可以打电话

var result = CacheService.
             GetObjectFromMemoryCacheWithDefParams<IEnumerable<dynamic>>(
                    casheName, 
                    getLpVideos(lng)
             );

你需要将一个字符串传递到 defGetValueFunc 中,并显式指定 T 的类型

public T GetObjectFromMemoryCacheWithDefParams<T>(string key, Func<string,T> defGetValueFunc) where T : class
{
  var result = _cache.Get(key) as T;    
  return result ?? defGetValueFunc(*somestring*);
}

var result = CacheService.GetObjectFromMemoryCacheWithDefParams<IEnumerable<dynamic>>(casheName, getLpVideos(lng)  );

你确定这正是你尝试编译的代码吗?错误是否真的发生在你说的地方?

如果是这样,那么在我看来,您的代码的问题在于您根本没有正确调用委托参数。您正在传递一个委托实例,该实例需要向其传递单个string参数。但是在您的代码中,您没有传递任何参数:

public T GetObjectFromMemoryCacheWithDefParams<T>(
    string key, Func<string, T> defGetValueFunc) where T : class
{
    var result = _cache.Get(key) as T;
    return result ?? defGetValueFunc(--> you need a parameter here! <--);//here error
}

我不知道您应该传递什么参数,因为您在帖子中包含的匿名方法甚至不使用该参数(除了检索被忽略的值)。但是你必须通过一些东西。

我认为这里的类型推断实际上没有任何问题。这个简单的示例与您的基本相同(除了我正确调用委托)编译得很好:

static T Method<T>(string s, Func<string, T> f) where T : class
{
    return f(s);
}
static void OtherMethod()
{
    Func<string, IEnumerable<dynamic>> f = l => new List<object>();
    Method("foo", f);
}

很明显,编译器可以在给定正确的代码的情况下推断出正确的类型。 :)