返回对象类型而不是字符串类型
本文关键字:类型 字符串 对象 返回 | 更新日期: 2023-09-27 18:16:43
public interface IApiUserProvider
{
Dictionary<Guid, string> UserNamesByToken { get; }
string this[Guid token] { get; }
}
public class ApiUserProvider : IApiUserProvider
{
private readonly ICacheProvider _cacheProvider;
private readonly IEntitySet<ApiUser> _apiUsers;
private string CacheKey
{
get
{
return string.Format("{0}-{1}", GetType().Name, "ApiUsersByToken");
}
}
public ApiUserProvider(ICacheProvider cacheProvider, IEntitySet<ApiUser> apiUsers)
{
_cacheProvider = cacheProvider;
_apiUsers = apiUsers;
}
public Dictionary<Guid, string> UserNamesByToken
{
get
{
return _cacheProvider.Get(CacheKey, () => _apiUsers.Where(u => u.IsActive).ToDictionary(u => u.Token, u => u.Name));
}
}
public string this[Guid token]
{
get { return UserNamesByToken.GetValueOrDefault(token); }
}
}
当我替换string this[Guid token] { get; }
与ApiUser this[Guid token] { get; }
我在这段代码中得到的错误如下
return string : cannot convert to object
return _cacheProvider.Get(CacheKey, () => _apiUsers.Where(u => u.IsActive).ToDictionary(u => u.Token, u => u.Name));
请告诉如何将其转换为对象类型
首先,您必须更新字段UserNamesByToken
public Dictionary<Guid, ApiUser> UserNamesByToken
{
get
{
return _cacheProvider.Get(CacheKey, () => _apiUsers.Where(u => u.IsActive).ToDictionary(u => u.Token, u => u));
}
}
不要忘记更新ToDictionary(u => u.Token, u => u)
然后更新你的IApiUserProvider接口
public interface IApiUserProvider
{
Dictionary<Guid, string> UserNamesByToken { get; }
ApiUser this[Guid token] { get; }
}
,之后更新索引
public string this[Guid token]
{
get { return UserNamesByToken.GetValueOrDefault(token); }
}
如果没有帮助,让我知道:)